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.
libagent/server.py ADDED
@@ -0,0 +1,400 @@
1
+ """UNIX-domain socket server for ssh-agent implementation."""
2
+ import contextlib
3
+ import hmac
4
+ import logging
5
+ import os
6
+ import socket
7
+ import subprocess
8
+ import threading
9
+
10
+ from . import util
11
+
12
+ log = logging.getLogger(__name__)
13
+
14
+
15
+ def remove_file(path, remove=os.remove, exists=os.path.exists):
16
+ """Remove file, and raise OSError if still exists."""
17
+ try:
18
+ remove(path)
19
+ except OSError:
20
+ if exists(path):
21
+ raise
22
+
23
+
24
+ @contextlib.contextmanager
25
+ def unix_domain_socket_server(sock_path):
26
+ """
27
+ Create UNIX-domain socket on specified path.
28
+
29
+ Listen on it, and delete it after the generated context is over.
30
+ """
31
+ log.debug('serving on %s', sock_path)
32
+ remove_file(sock_path)
33
+
34
+ server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
35
+ server.bind(sock_path)
36
+ server.listen(1)
37
+ try:
38
+ yield server
39
+ finally:
40
+ remove_file(sock_path)
41
+
42
+
43
+ class FDServer:
44
+ """File-descriptor based server (for NeoPG)."""
45
+
46
+ def __init__(self, fd):
47
+ """C-tor."""
48
+ self.fd = fd
49
+ self.sock = socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_STREAM)
50
+
51
+ def accept(self):
52
+ """Use the same socket for I/O."""
53
+ return self, None
54
+
55
+ def recv(self, n):
56
+ """Forward to underlying socket."""
57
+ return self.sock.recv(n)
58
+
59
+ def sendall(self, data):
60
+ """Forward to underlying socket."""
61
+ return self.sock.sendall(data)
62
+
63
+ def close(self):
64
+ """Not needed."""
65
+
66
+ def settimeout(self, _):
67
+ """Not needed."""
68
+
69
+ def getsockname(self):
70
+ """Simple representation."""
71
+ return '<fd: {}>'.format(self.fd)
72
+
73
+
74
+ @contextlib.contextmanager
75
+ def unix_domain_socket_server_from_fd(fd):
76
+ """Build UDS-based socket server from a file descriptor."""
77
+ yield FDServer(fd)
78
+
79
+
80
+ ASSUAN_NONCE_LEN = 16
81
+
82
+
83
+ class AssuanNonceServer:
84
+ """
85
+ libassuan's socket emulation, as GnuPG for Windows uses it.
86
+
87
+ The socket "file" holds a TCP port on 127.0.0.1, a newline, and a 16-byte
88
+ nonce. A client connects to the port and must send the nonce before
89
+ anything else; a connection that does not is dropped. The nonce is what
90
+ keeps other local users out, and the file's place in the user's own
91
+ profile is what keeps the nonce from them.
92
+ """
93
+
94
+ def __init__(self, sock, nonce):
95
+ """C-tor."""
96
+ self.sock = sock
97
+ self.nonce = nonce
98
+
99
+ def accept(self):
100
+ """Wait for a connection that starts with the nonce."""
101
+ while True:
102
+ conn, addr = self.sock.accept()
103
+ conn.settimeout(10) # a silent client must not block the agent
104
+ received = b''
105
+ try:
106
+ while len(received) < ASSUAN_NONCE_LEN:
107
+ chunk = conn.recv(ASSUAN_NONCE_LEN - len(received))
108
+ if not chunk:
109
+ break
110
+ received += chunk
111
+ except OSError:
112
+ pass
113
+ if hmac.compare_digest(received, self.nonce):
114
+ return conn, addr
115
+ log.warning('dropping a connection without the socket nonce')
116
+ conn.close()
117
+
118
+ def getsockname(self):
119
+ """Forward to underlying socket."""
120
+ return self.sock.getsockname()
121
+
122
+
123
+ @contextlib.contextmanager
124
+ def assuan_nonce_socket_server(sock_path):
125
+ """
126
+ Serve libassuan's Windows socket emulation at the specified path.
127
+
128
+ Listen on a loopback port, write the port and a fresh nonce to sock_path,
129
+ and delete the file after the generated context is over.
130
+ """
131
+ log.debug('serving on %s', sock_path)
132
+ remove_file(sock_path)
133
+
134
+ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
135
+ server.bind(('127.0.0.1', 0))
136
+ server.listen(1)
137
+ nonce = os.urandom(ASSUAN_NONCE_LEN)
138
+ with open(sock_path, 'wb') as f:
139
+ f.write('{}\n'.format(server.getsockname()[1]).encode('ascii') + nonce)
140
+ try:
141
+ yield AssuanNonceServer(server, nonce)
142
+ finally:
143
+ server.close()
144
+ remove_file(sock_path)
145
+
146
+
147
+ WINDOWS_PIPE_BUFSIZE = 65536
148
+
149
+
150
+ class NamedPipeConnection:
151
+ """
152
+ One client of a Windows named pipe, with the calls the agent makes on a socket.
153
+
154
+ Overlapped I/O, because the pipe is opened overlapped (so accept() can time out).
155
+ """
156
+
157
+ def __init__(self, handle):
158
+ """C-tor."""
159
+ self.handle = handle
160
+
161
+ def recv(self, n):
162
+ """Read up to n bytes; b'' when the client has gone (the agent's EOF)."""
163
+ import _winapi # pylint: disable=import-outside-toplevel,import-error
164
+ try:
165
+ ov, err = _winapi.ReadFile(self.handle, n, overlapped=True)
166
+ except OSError as e:
167
+ if getattr(e, 'winerror', None) == _winapi.ERROR_BROKEN_PIPE:
168
+ return b''
169
+ raise
170
+ try:
171
+ if err == _winapi.ERROR_IO_PENDING:
172
+ _winapi.WaitForMultipleObjects([ov.event], False, _winapi.INFINITE)
173
+ except BaseException:
174
+ ov.cancel()
175
+ raise
176
+ try:
177
+ nread, err = ov.GetOverlappedResult(True)
178
+ except OSError as e:
179
+ if getattr(e, 'winerror', None) == _winapi.ERROR_BROKEN_PIPE:
180
+ return b''
181
+ raise
182
+ return bytes(ov.getbuffer()[:nread])
183
+
184
+ def sendall(self, data):
185
+ """Write all of data."""
186
+ import _winapi # pylint: disable=import-outside-toplevel,import-error
187
+ ov, err = _winapi.WriteFile(self.handle, data, overlapped=True)
188
+ try:
189
+ if err == _winapi.ERROR_IO_PENDING:
190
+ _winapi.WaitForMultipleObjects([ov.event], False, _winapi.INFINITE)
191
+ except BaseException:
192
+ ov.cancel()
193
+ raise
194
+ nwritten, err = ov.GetOverlappedResult(True)
195
+ if nwritten != len(data):
196
+ raise OSError('short write to the agent pipe: {} of {}'.format(nwritten, len(data)))
197
+
198
+ def settimeout(self, _):
199
+ """Not needed: the agent waits on a client for as long as it stays."""
200
+
201
+ def close(self):
202
+ """Close this client's pipe instance."""
203
+ import _winapi # pylint: disable=import-outside-toplevel,import-error
204
+ if self.handle is not None:
205
+ _winapi.CloseHandle(self.handle)
206
+ self.handle = None
207
+
208
+
209
+ class NamedPipeServer:
210
+ """
211
+ An ssh-agent listener on a Windows named pipe - what Windows' OpenSSH looks for.
212
+
213
+ CPython on Windows has no socket.AF_UNIX, so the UNIX-domain server cannot
214
+ start there. Each accept() serves one pipe instance (byte mode) and makes the
215
+ next. Remote clients are rejected (PIPE_REJECT_REMOTE_CLIENTS), and the first
216
+ instance is created with FILE_FLAG_FIRST_PIPE_INSTANCE, so a name another
217
+ process already holds fails at start instead of letting it impersonate the
218
+ agent. The pipe has Windows' default security for a named pipe: only this
219
+ user, SYSTEM and Administrators may write to it.
220
+ """
221
+
222
+ PIPE_REJECT_REMOTE_CLIENTS = 0x00000008
223
+ # Win32's byte-mode flags are 0, and _winapi does not name them; spelled out
224
+ # so the mode is visible: a byte stream, as ssh writes it, not messages.
225
+ PIPE_TYPE_BYTE = 0x00000000
226
+ PIPE_READMODE_BYTE = 0x00000000
227
+
228
+ def __init__(self, name):
229
+ """C-tor."""
230
+ self.name = name
231
+ self.timeout = None
232
+ self._pending = None # (handle, overlapped) waiting for a client
233
+ self._first = True
234
+
235
+ def _listen(self):
236
+ import _winapi # pylint: disable=import-outside-toplevel,import-error
237
+ open_mode = _winapi.PIPE_ACCESS_DUPLEX | _winapi.FILE_FLAG_OVERLAPPED
238
+ if self._first:
239
+ open_mode |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
240
+ handle = _winapi.CreateNamedPipe(
241
+ self.name, open_mode,
242
+ self.PIPE_TYPE_BYTE | self.PIPE_READMODE_BYTE | _winapi.PIPE_WAIT
243
+ | self.PIPE_REJECT_REMOTE_CLIENTS,
244
+ _winapi.PIPE_UNLIMITED_INSTANCES, WINDOWS_PIPE_BUFSIZE, WINDOWS_PIPE_BUFSIZE,
245
+ _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL)
246
+ self._first = False
247
+ try:
248
+ ov = _winapi.ConnectNamedPipe(handle, overlapped=True)
249
+ except OSError:
250
+ _winapi.CloseHandle(handle)
251
+ raise
252
+ self._pending = (handle, ov)
253
+
254
+ def start(self):
255
+ """Create the first instance now, so a taken name fails before anything runs."""
256
+ self._listen()
257
+
258
+ def settimeout(self, timeout):
259
+ """How long accept() waits before raising socket.timeout (None: forever)."""
260
+ self.timeout = timeout
261
+
262
+ def accept(self):
263
+ """Wait for a client on the pending instance; raise socket.timeout if none came."""
264
+ import _winapi # pylint: disable=import-outside-toplevel,import-error
265
+ if self._pending is None:
266
+ self._listen()
267
+ handle, ov = self._pending
268
+ wait_ms = _winapi.INFINITE if self.timeout is None else int(self.timeout * 1000)
269
+ if _winapi.WaitForMultipleObjects([ov.event], False, wait_ms) == _winapi.WAIT_TIMEOUT:
270
+ raise socket.timeout()
271
+ self._pending = None
272
+ try:
273
+ ov.GetOverlappedResult(True)
274
+ except OSError as e:
275
+ # ERROR_NO_DATA: the client connected and left already - nothing to serve
276
+ _winapi.CloseHandle(handle)
277
+ if getattr(e, 'winerror', None) == _winapi.ERROR_NO_DATA:
278
+ raise socket.timeout() from e
279
+ raise
280
+ return NamedPipeConnection(handle), None
281
+
282
+ def getsockname(self):
283
+ """The pipe's name."""
284
+ return self.name
285
+
286
+ def close(self):
287
+ """Stop listening."""
288
+ import _winapi # pylint: disable=import-outside-toplevel,import-error
289
+ if self._pending is not None:
290
+ handle, ov = self._pending
291
+ self._pending = None
292
+ ov.cancel()
293
+ _winapi.CloseHandle(handle)
294
+
295
+
296
+ @contextlib.contextmanager
297
+ def named_pipe_server(pipe_name):
298
+ r"""
299
+ Serve the ssh-agent on a Windows named pipe (e.g. \\.\pipe\onlykey-agent-...).
300
+
301
+ The Windows counterpart of unix_domain_socket_server(); the pipe goes away
302
+ when the generated context is over.
303
+ """
304
+ log.debug('serving on %s', pipe_name)
305
+ pipe_server = NamedPipeServer(pipe_name)
306
+ pipe_server.start()
307
+ try:
308
+ yield pipe_server
309
+ finally:
310
+ pipe_server.close()
311
+
312
+
313
+ def handle_connection(conn, handler, mutex):
314
+ """
315
+ Handle a single connection using the specified protocol handler in a loop.
316
+
317
+ Since this function may be called concurrently from server_thread,
318
+ the specified mutex is used to synchronize the device handling.
319
+
320
+ Exit when EOFError is raised.
321
+ All other exceptions are logged as warnings.
322
+ """
323
+ try:
324
+ log.debug('welcome agent')
325
+ with contextlib.closing(conn):
326
+ while True:
327
+ msg = util.read_frame(conn)
328
+ with mutex:
329
+ reply = handler.handle(msg=msg)
330
+ util.send(conn, reply)
331
+ except EOFError:
332
+ log.debug('goodbye agent')
333
+ except Exception as e: # pylint: disable=broad-except
334
+ log.warning('error: %s', e, exc_info=True)
335
+
336
+
337
+ def retry(func, exception_type, quit_event):
338
+ """
339
+ Run the function, retrying when the specified exception_type occurs.
340
+
341
+ Poll quit_event on each iteration, to be responsive to an external
342
+ exit request.
343
+ """
344
+ while True:
345
+ if quit_event.is_set():
346
+ raise StopIteration
347
+ try:
348
+ return func()
349
+ except exception_type:
350
+ pass
351
+
352
+
353
+ def server_thread(sock, handle_conn, quit_event):
354
+ """Run a server on the specified socket."""
355
+ log.debug('server thread started')
356
+
357
+ def accept_connection():
358
+ conn, _ = sock.accept()
359
+ conn.settimeout(None)
360
+ return conn
361
+
362
+ while True:
363
+ log.debug('waiting for connection on %s', sock.getsockname())
364
+ try:
365
+ conn = retry(accept_connection, socket.timeout, quit_event)
366
+ except StopIteration:
367
+ log.debug('server stopped')
368
+ break
369
+ # Handle connections from SSH concurrently.
370
+ threading.Thread(target=handle_conn,
371
+ kwargs={'conn': conn}).start()
372
+ log.debug('server thread stopped')
373
+
374
+
375
+ @contextlib.contextmanager
376
+ def spawn(func, kwargs):
377
+ """Spawn a thread, and join it after the context is over."""
378
+ t = threading.Thread(target=func, kwargs=kwargs)
379
+ t.start()
380
+ yield
381
+ t.join()
382
+
383
+
384
+ def run_process(command, environ):
385
+ """
386
+ Run the specified process and wait until it finishes.
387
+
388
+ Use environ dict for environment variables.
389
+ """
390
+ log.info('running %r with %r', command, environ)
391
+ env = dict(os.environ)
392
+ env.update(environ)
393
+ try:
394
+ p = subprocess.Popen(args=command, env=env)
395
+ except OSError as e:
396
+ raise OSError('cannot run %r: %s' % (command, e)) from e
397
+ log.debug('subprocess %d is running', p.pid)
398
+ ret = p.wait()
399
+ log.debug('subprocess %d exited: %d', p.pid, ret)
400
+ return ret
@@ -0,0 +1,127 @@
1
+ """TREZOR support for Ed25519 signify/minisign signatures."""
2
+
3
+ import argparse
4
+ import binascii
5
+ import contextlib
6
+ import functools
7
+ import hashlib
8
+ import logging
9
+ import os
10
+ import re
11
+ import struct
12
+ import subprocess
13
+ import sys
14
+ import time
15
+
16
+ import semver
17
+
18
+ from .. import formats, server, util
19
+ from ..device import interface, ui
20
+
21
+ log = logging.getLogger(__name__)
22
+
23
+
24
+ def _create_identity(user_id):
25
+ result = interface.Identity(identity_str='signify://', curve_name='ed25519')
26
+ result.identity_dict['host'] = user_id
27
+ return result
28
+
29
+
30
+ class Client:
31
+ """Sign messages and get public keys from a hardware device."""
32
+
33
+ def __init__(self, device):
34
+ """C-tor."""
35
+ self.device = device
36
+
37
+ def pubkey(self, identity):
38
+ """Return public key as VerifyingKey object."""
39
+ with self.device:
40
+ return bytes(self.device.pubkey(ecdh=False, identity=identity))
41
+
42
+ def sign_with_pubkey(self, identity, data):
43
+ """Sign the data and return a signature."""
44
+ log.info('please confirm Signify signature on %s for "%s"...',
45
+ self.device, identity.to_string())
46
+ log.debug('signing data: %s', util.hexlify(data))
47
+ with self.device:
48
+ sig, pubkey = self.device.sign_with_pubkey(blob=data, identity=identity)
49
+ assert len(sig) == 64
50
+ assert len(pubkey) == 33
51
+ assert pubkey[:1] == b"\x00"
52
+ return sig, pubkey[1:]
53
+
54
+
55
+ ALG_SIGNIFY = b'Ed'
56
+ ALG_MINISIGN = b'ED' # prehashes the data before signing
57
+
58
+
59
+ def format_payload(pubkey, data, sig_alg):
60
+ """See http://www.openbsd.org/papers/bsdcan-signify.html for details."""
61
+ keynum = hashlib.sha256(pubkey).digest()[:8]
62
+ return binascii.b2a_base64(sig_alg + keynum + data).decode("ascii")
63
+
64
+
65
+ def run_pubkey(device_type, args):
66
+ """Export hardware-based Signify public key."""
67
+ util.setup_logging(verbosity=args.verbose)
68
+ log.warning('This Signify tool is still in EXPERIMENTAL mode, '
69
+ 'so please note that the key derivation, API, and features '
70
+ 'may change without backwards compatibility!')
71
+
72
+ identity = _create_identity(user_id=args.user_id)
73
+ pubkey = Client(device=device_type()).pubkey(identity=identity)
74
+ comment = f'untrusted comment: identity {identity.to_string()}\n'
75
+ payload = format_payload(pubkey=pubkey, data=pubkey, sig_alg=ALG_SIGNIFY)
76
+ print(comment + payload, end="")
77
+
78
+
79
+ def run_sign(device_type, args):
80
+ """Prehash & sign an input blob using Ed25519."""
81
+ util.setup_logging(verbosity=args.verbose)
82
+ identity = _create_identity(user_id=args.user_id)
83
+
84
+ data_to_sign = sys.stdin.buffer.read()
85
+ sig_alg = ALG_SIGNIFY
86
+ if args.prehash:
87
+ # See https://github.com/jedisct1/minisign/commit/6e1023d20758b6fdb2a4b697213b0bf608ba4020
88
+ # Released in https://github.com/jedisct1/minisign/releases/tag/0.6
89
+ sig_alg = ALG_MINISIGN
90
+ data_to_sign = hashlib.blake2b(data_to_sign).digest()
91
+
92
+ sig, pubkey = Client(device=device_type()).sign_with_pubkey(identity, data_to_sign)
93
+ pubkey_str = format_payload(pubkey=pubkey, data=pubkey, sig_alg=sig_alg)
94
+ sig_str = format_payload(pubkey=pubkey, data=sig, sig_alg=sig_alg)
95
+ untrusted_comment = f'untrusted comment: pubkey {pubkey_str}'
96
+ print(untrusted_comment + sig_str, end="")
97
+
98
+ comment_to_sign = sig + args.comment.encode()
99
+ sig, _ = Client(device=device_type()).sign_with_pubkey(identity, comment_to_sign)
100
+ sig_str = binascii.b2a_base64(sig).decode("ascii")
101
+ print(f'trusted comment: {args.comment}\n' + sig_str, end="")
102
+
103
+
104
+ def main(device_type):
105
+ """Parse command-line arguments."""
106
+ parser = argparse.ArgumentParser()
107
+
108
+ subparsers = parser.add_subparsers(title='Action', dest='action')
109
+ subparsers.required = True
110
+
111
+ p = subparsers.add_parser('pubkey')
112
+ p.add_argument('user_id')
113
+ p.add_argument('-v', '--verbose', default=0, action='count')
114
+ p.set_defaults(func=run_pubkey)
115
+
116
+ p = subparsers.add_parser('sign')
117
+ p.add_argument('user_id')
118
+ p.add_argument('-v', '--verbose', default=0, action='count')
119
+ p.add_argument('-c', '--comment', default=time.asctime())
120
+ p.add_argument('-H', '--prehash', default=False, action='store_true')
121
+ p.set_defaults(func=run_sign)
122
+
123
+ args = parser.parse_args()
124
+ device_type.ui = ui.UI(device_type=device_type, config=vars(args))
125
+ device_type.ui.cached_passphrase_ack = util.ExpiringCache(seconds=float(60))
126
+
127
+ return args.func(device_type=device_type, args=args)