|
1 | 1 | #!/usr/bin/env python3
|
2 | 2 |
|
3 | 3 | from argparse import ArgumentParser
|
| 4 | +from binascii import hexlify |
4 | 5 | from collections import namedtuple as ntup
|
5 | 6 | from os import path
|
6 | 7 | from pathlib import Path
|
|
13 | 14 | CONFIG_FILE = '~/.ssh/ckssh_config'
|
14 | 15 | DEVNULL = open(os.devnull, 'w')
|
15 | 16 |
|
| 17 | +############################################################ |
| 18 | +# SSH agent protocol functions |
| 19 | + |
| 20 | +class SSHAgentProtoError(RuntimeError): |
| 21 | + pass |
| 22 | + |
| 23 | +def read_agentproto_int(stream, length): |
| 24 | + bs = stream.read(length) |
| 25 | + if len(bs) != length: |
| 26 | + raise SSHAgentProtoError('Short int: {}'.format(bs)) |
| 27 | + return int.from_bytes(bs, byteorder='big') |
| 28 | + |
| 29 | +def read_agentproto_bstr(stream): |
| 30 | + length = read_agentproto_int(stream, 4) |
| 31 | + bs = stream.read(length) |
| 32 | + if len(bs) != length: |
| 33 | + raise SSHAgentProtoError('Short string: {}'.format(bs)) |
| 34 | + return bs |
| 35 | + |
| 36 | +def read_agentproto_idcomments(stream): |
| 37 | + ''' From the given I/O stream, Read and parse an |
| 38 | + ``SSH2_AGENT_IDENTITIES_ANSWER`` response to an |
| 39 | + ``SSH2_AGENTC_REQUEST_IDENTITIES`` request. |
| 40 | + Return a list with the comment for each identity. |
| 41 | +
|
| 42 | + For protocol details see section 2.5.2 of |
| 43 | + <http://api.libssh.org/rfc/PROTOCOL.agent>. |
| 44 | + ''' |
| 45 | + # We don't actually use the message length, instead relying on |
| 46 | + # the count of keys and string lengths, but we parse it to make |
| 47 | + # sure this isn't a bad message. |
| 48 | + msglen = read_agentproto_int(stream, 4) |
| 49 | + |
| 50 | + msgtype = read_agentproto_int(stream, 1) |
| 51 | + if msgtype != 0xC: |
| 52 | + raise SSHAgentProtoError( |
| 53 | + 'Unknown message type: {}'.format(msgtype)) |
| 54 | + |
| 55 | + keycount = read_agentproto_int(stream, 4) |
| 56 | + comments = [] |
| 57 | + for i in range(0, keycount): |
| 58 | + read_agentproto_bstr(stream) # key blob |
| 59 | + bs = read_agentproto_bstr(stream) # key comment |
| 60 | + comments.append(bs.decode('ascii')) |
| 61 | + return comments |
| 62 | + |
| 63 | + raise SSHAgentProtoError() |
| 64 | + return [] |
| 65 | + |
16 | 66 | ############################################################
|
17 | 67 | # Compartment classes and functions
|
18 | 68 |
|
|
0 commit comments