id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
9,900
|
romanz/trezor-agent
|
libagent/formats.py
|
export_public_key
|
def export_public_key(vk, label):
"""
Export public key to text format.
The resulting string can be written into a .pub file or
appended to the ~/.ssh/authorized_keys file.
"""
key_type, blob = serialize_verifying_key(vk)
log.debug('fingerprint: %s', fingerprint(blob))
b64 = base64.b64encode(blob).decode('ascii')
return u'{} {} {}\n'.format(key_type.decode('ascii'), b64, label)
|
python
|
def export_public_key(vk, label):
"""
Export public key to text format.
The resulting string can be written into a .pub file or
appended to the ~/.ssh/authorized_keys file.
"""
key_type, blob = serialize_verifying_key(vk)
log.debug('fingerprint: %s', fingerprint(blob))
b64 = base64.b64encode(blob).decode('ascii')
return u'{} {} {}\n'.format(key_type.decode('ascii'), b64, label)
|
[
"def",
"export_public_key",
"(",
"vk",
",",
"label",
")",
":",
"key_type",
",",
"blob",
"=",
"serialize_verifying_key",
"(",
"vk",
")",
"log",
".",
"debug",
"(",
"'fingerprint: %s'",
",",
"fingerprint",
"(",
"blob",
")",
")",
"b64",
"=",
"base64",
".",
"b64encode",
"(",
"blob",
")",
".",
"decode",
"(",
"'ascii'",
")",
"return",
"u'{} {} {}\\n'",
".",
"format",
"(",
"key_type",
".",
"decode",
"(",
"'ascii'",
")",
",",
"b64",
",",
"label",
")"
] |
Export public key to text format.
The resulting string can be written into a .pub file or
appended to the ~/.ssh/authorized_keys file.
|
[
"Export",
"public",
"key",
"to",
"text",
"format",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/formats.py#L181-L191
|
9,901
|
romanz/trezor-agent
|
libagent/formats.py
|
import_public_key
|
def import_public_key(line):
"""Parse public key textual format, as saved at a .pub file."""
log.debug('loading SSH public key: %r', line)
file_type, base64blob, name = line.split()
blob = base64.b64decode(base64blob)
result = parse_pubkey(blob)
result['name'] = name.encode('utf-8')
assert result['type'] == file_type.encode('ascii')
log.debug('loaded %s public key: %s', file_type, result['fingerprint'])
return result
|
python
|
def import_public_key(line):
"""Parse public key textual format, as saved at a .pub file."""
log.debug('loading SSH public key: %r', line)
file_type, base64blob, name = line.split()
blob = base64.b64decode(base64blob)
result = parse_pubkey(blob)
result['name'] = name.encode('utf-8')
assert result['type'] == file_type.encode('ascii')
log.debug('loaded %s public key: %s', file_type, result['fingerprint'])
return result
|
[
"def",
"import_public_key",
"(",
"line",
")",
":",
"log",
".",
"debug",
"(",
"'loading SSH public key: %r'",
",",
"line",
")",
"file_type",
",",
"base64blob",
",",
"name",
"=",
"line",
".",
"split",
"(",
")",
"blob",
"=",
"base64",
".",
"b64decode",
"(",
"base64blob",
")",
"result",
"=",
"parse_pubkey",
"(",
"blob",
")",
"result",
"[",
"'name'",
"]",
"=",
"name",
".",
"encode",
"(",
"'utf-8'",
")",
"assert",
"result",
"[",
"'type'",
"]",
"==",
"file_type",
".",
"encode",
"(",
"'ascii'",
")",
"log",
".",
"debug",
"(",
"'loaded %s public key: %s'",
",",
"file_type",
",",
"result",
"[",
"'fingerprint'",
"]",
")",
"return",
"result"
] |
Parse public key textual format, as saved at a .pub file.
|
[
"Parse",
"public",
"key",
"textual",
"format",
"as",
"saved",
"at",
"a",
".",
"pub",
"file",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/formats.py#L194-L203
|
9,902
|
romanz/trezor-agent
|
libagent/gpg/decode.py
|
parse_packets
|
def parse_packets(stream):
"""
Support iterative parsing of available GPG packets.
See https://tools.ietf.org/html/rfc4880#section-4.2 for details.
"""
reader = util.Reader(stream)
while True:
try:
value = reader.readfmt('B')
except EOFError:
return
log.debug('prefix byte: %s', bin(value))
assert util.bit(value, 7) == 1
tag = util.low_bits(value, 6)
if util.bit(value, 6) == 0:
length_type = util.low_bits(tag, 2)
tag = tag >> 2
fmt = {0: '>B', 1: '>H', 2: '>L'}[length_type]
packet_size = reader.readfmt(fmt)
else:
first = reader.readfmt('B')
if first < 192:
packet_size = first
elif first < 224:
packet_size = ((first - 192) << 8) + reader.readfmt('B') + 192
elif first == 255:
packet_size = reader.readfmt('>L')
else:
log.error('Partial Body Lengths unsupported')
log.debug('packet length: %d', packet_size)
packet_data = reader.read(packet_size)
packet_type = PACKET_TYPES.get(tag)
p = {'type': 'unknown', 'tag': tag, 'raw': packet_data}
if packet_type is not None:
try:
p = packet_type(util.Reader(io.BytesIO(packet_data)))
p['tag'] = tag
except ValueError:
log.exception('Skipping packet: %s', util.hexlify(packet_data))
log.debug('packet "%s": %s', p['type'], p)
yield p
|
python
|
def parse_packets(stream):
"""
Support iterative parsing of available GPG packets.
See https://tools.ietf.org/html/rfc4880#section-4.2 for details.
"""
reader = util.Reader(stream)
while True:
try:
value = reader.readfmt('B')
except EOFError:
return
log.debug('prefix byte: %s', bin(value))
assert util.bit(value, 7) == 1
tag = util.low_bits(value, 6)
if util.bit(value, 6) == 0:
length_type = util.low_bits(tag, 2)
tag = tag >> 2
fmt = {0: '>B', 1: '>H', 2: '>L'}[length_type]
packet_size = reader.readfmt(fmt)
else:
first = reader.readfmt('B')
if first < 192:
packet_size = first
elif first < 224:
packet_size = ((first - 192) << 8) + reader.readfmt('B') + 192
elif first == 255:
packet_size = reader.readfmt('>L')
else:
log.error('Partial Body Lengths unsupported')
log.debug('packet length: %d', packet_size)
packet_data = reader.read(packet_size)
packet_type = PACKET_TYPES.get(tag)
p = {'type': 'unknown', 'tag': tag, 'raw': packet_data}
if packet_type is not None:
try:
p = packet_type(util.Reader(io.BytesIO(packet_data)))
p['tag'] = tag
except ValueError:
log.exception('Skipping packet: %s', util.hexlify(packet_data))
log.debug('packet "%s": %s', p['type'], p)
yield p
|
[
"def",
"parse_packets",
"(",
"stream",
")",
":",
"reader",
"=",
"util",
".",
"Reader",
"(",
"stream",
")",
"while",
"True",
":",
"try",
":",
"value",
"=",
"reader",
".",
"readfmt",
"(",
"'B'",
")",
"except",
"EOFError",
":",
"return",
"log",
".",
"debug",
"(",
"'prefix byte: %s'",
",",
"bin",
"(",
"value",
")",
")",
"assert",
"util",
".",
"bit",
"(",
"value",
",",
"7",
")",
"==",
"1",
"tag",
"=",
"util",
".",
"low_bits",
"(",
"value",
",",
"6",
")",
"if",
"util",
".",
"bit",
"(",
"value",
",",
"6",
")",
"==",
"0",
":",
"length_type",
"=",
"util",
".",
"low_bits",
"(",
"tag",
",",
"2",
")",
"tag",
"=",
"tag",
">>",
"2",
"fmt",
"=",
"{",
"0",
":",
"'>B'",
",",
"1",
":",
"'>H'",
",",
"2",
":",
"'>L'",
"}",
"[",
"length_type",
"]",
"packet_size",
"=",
"reader",
".",
"readfmt",
"(",
"fmt",
")",
"else",
":",
"first",
"=",
"reader",
".",
"readfmt",
"(",
"'B'",
")",
"if",
"first",
"<",
"192",
":",
"packet_size",
"=",
"first",
"elif",
"first",
"<",
"224",
":",
"packet_size",
"=",
"(",
"(",
"first",
"-",
"192",
")",
"<<",
"8",
")",
"+",
"reader",
".",
"readfmt",
"(",
"'B'",
")",
"+",
"192",
"elif",
"first",
"==",
"255",
":",
"packet_size",
"=",
"reader",
".",
"readfmt",
"(",
"'>L'",
")",
"else",
":",
"log",
".",
"error",
"(",
"'Partial Body Lengths unsupported'",
")",
"log",
".",
"debug",
"(",
"'packet length: %d'",
",",
"packet_size",
")",
"packet_data",
"=",
"reader",
".",
"read",
"(",
"packet_size",
")",
"packet_type",
"=",
"PACKET_TYPES",
".",
"get",
"(",
"tag",
")",
"p",
"=",
"{",
"'type'",
":",
"'unknown'",
",",
"'tag'",
":",
"tag",
",",
"'raw'",
":",
"packet_data",
"}",
"if",
"packet_type",
"is",
"not",
"None",
":",
"try",
":",
"p",
"=",
"packet_type",
"(",
"util",
".",
"Reader",
"(",
"io",
".",
"BytesIO",
"(",
"packet_data",
")",
")",
")",
"p",
"[",
"'tag'",
"]",
"=",
"tag",
"except",
"ValueError",
":",
"log",
".",
"exception",
"(",
"'Skipping packet: %s'",
",",
"util",
".",
"hexlify",
"(",
"packet_data",
")",
")",
"log",
".",
"debug",
"(",
"'packet \"%s\": %s'",
",",
"p",
"[",
"'type'",
"]",
",",
"p",
")",
"yield",
"p"
] |
Support iterative parsing of available GPG packets.
See https://tools.ietf.org/html/rfc4880#section-4.2 for details.
|
[
"Support",
"iterative",
"parsing",
"of",
"available",
"GPG",
"packets",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/decode.py#L215-L261
|
9,903
|
romanz/trezor-agent
|
libagent/gpg/decode.py
|
digest_packets
|
def digest_packets(packets, hasher):
"""Compute digest on specified packets, according to '_to_hash' field."""
data_to_hash = io.BytesIO()
for p in packets:
data_to_hash.write(p['_to_hash'])
hasher.update(data_to_hash.getvalue())
return hasher.digest()
|
python
|
def digest_packets(packets, hasher):
"""Compute digest on specified packets, according to '_to_hash' field."""
data_to_hash = io.BytesIO()
for p in packets:
data_to_hash.write(p['_to_hash'])
hasher.update(data_to_hash.getvalue())
return hasher.digest()
|
[
"def",
"digest_packets",
"(",
"packets",
",",
"hasher",
")",
":",
"data_to_hash",
"=",
"io",
".",
"BytesIO",
"(",
")",
"for",
"p",
"in",
"packets",
":",
"data_to_hash",
".",
"write",
"(",
"p",
"[",
"'_to_hash'",
"]",
")",
"hasher",
".",
"update",
"(",
"data_to_hash",
".",
"getvalue",
"(",
")",
")",
"return",
"hasher",
".",
"digest",
"(",
")"
] |
Compute digest on specified packets, according to '_to_hash' field.
|
[
"Compute",
"digest",
"on",
"specified",
"packets",
"according",
"to",
"_to_hash",
"field",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/decode.py#L264-L270
|
9,904
|
romanz/trezor-agent
|
libagent/gpg/decode.py
|
load_by_keygrip
|
def load_by_keygrip(pubkey_bytes, keygrip):
"""Return public key and first user ID for specified keygrip."""
stream = io.BytesIO(pubkey_bytes)
packets = list(parse_packets(stream))
packets_per_pubkey = []
for p in packets:
if p['type'] == 'pubkey':
# Add a new packet list for each pubkey.
packets_per_pubkey.append([])
packets_per_pubkey[-1].append(p)
for packets in packets_per_pubkey:
user_ids = [p for p in packets if p['type'] == 'user_id']
for p in packets:
if p.get('keygrip') == keygrip:
return p, user_ids
raise KeyError('{} keygrip not found'.format(util.hexlify(keygrip)))
|
python
|
def load_by_keygrip(pubkey_bytes, keygrip):
"""Return public key and first user ID for specified keygrip."""
stream = io.BytesIO(pubkey_bytes)
packets = list(parse_packets(stream))
packets_per_pubkey = []
for p in packets:
if p['type'] == 'pubkey':
# Add a new packet list for each pubkey.
packets_per_pubkey.append([])
packets_per_pubkey[-1].append(p)
for packets in packets_per_pubkey:
user_ids = [p for p in packets if p['type'] == 'user_id']
for p in packets:
if p.get('keygrip') == keygrip:
return p, user_ids
raise KeyError('{} keygrip not found'.format(util.hexlify(keygrip)))
|
[
"def",
"load_by_keygrip",
"(",
"pubkey_bytes",
",",
"keygrip",
")",
":",
"stream",
"=",
"io",
".",
"BytesIO",
"(",
"pubkey_bytes",
")",
"packets",
"=",
"list",
"(",
"parse_packets",
"(",
"stream",
")",
")",
"packets_per_pubkey",
"=",
"[",
"]",
"for",
"p",
"in",
"packets",
":",
"if",
"p",
"[",
"'type'",
"]",
"==",
"'pubkey'",
":",
"# Add a new packet list for each pubkey.",
"packets_per_pubkey",
".",
"append",
"(",
"[",
"]",
")",
"packets_per_pubkey",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"p",
")",
"for",
"packets",
"in",
"packets_per_pubkey",
":",
"user_ids",
"=",
"[",
"p",
"for",
"p",
"in",
"packets",
"if",
"p",
"[",
"'type'",
"]",
"==",
"'user_id'",
"]",
"for",
"p",
"in",
"packets",
":",
"if",
"p",
".",
"get",
"(",
"'keygrip'",
")",
"==",
"keygrip",
":",
"return",
"p",
",",
"user_ids",
"raise",
"KeyError",
"(",
"'{} keygrip not found'",
".",
"format",
"(",
"util",
".",
"hexlify",
"(",
"keygrip",
")",
")",
")"
] |
Return public key and first user ID for specified keygrip.
|
[
"Return",
"public",
"key",
"and",
"first",
"user",
"ID",
"for",
"specified",
"keygrip",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/decode.py#L284-L300
|
9,905
|
romanz/trezor-agent
|
libagent/gpg/decode.py
|
load_signature
|
def load_signature(stream, original_data):
"""Load signature from stream, and compute GPG digest for verification."""
signature, = list(parse_packets((stream)))
hash_alg = HASH_ALGORITHMS[signature['hash_alg']]
digest = digest_packets([{'_to_hash': original_data}, signature],
hasher=hashlib.new(hash_alg))
assert signature['hash_prefix'] == digest[:2]
return signature, digest
|
python
|
def load_signature(stream, original_data):
"""Load signature from stream, and compute GPG digest for verification."""
signature, = list(parse_packets((stream)))
hash_alg = HASH_ALGORITHMS[signature['hash_alg']]
digest = digest_packets([{'_to_hash': original_data}, signature],
hasher=hashlib.new(hash_alg))
assert signature['hash_prefix'] == digest[:2]
return signature, digest
|
[
"def",
"load_signature",
"(",
"stream",
",",
"original_data",
")",
":",
"signature",
",",
"=",
"list",
"(",
"parse_packets",
"(",
"(",
"stream",
")",
")",
")",
"hash_alg",
"=",
"HASH_ALGORITHMS",
"[",
"signature",
"[",
"'hash_alg'",
"]",
"]",
"digest",
"=",
"digest_packets",
"(",
"[",
"{",
"'_to_hash'",
":",
"original_data",
"}",
",",
"signature",
"]",
",",
"hasher",
"=",
"hashlib",
".",
"new",
"(",
"hash_alg",
")",
")",
"assert",
"signature",
"[",
"'hash_prefix'",
"]",
"==",
"digest",
"[",
":",
"2",
"]",
"return",
"signature",
",",
"digest"
] |
Load signature from stream, and compute GPG digest for verification.
|
[
"Load",
"signature",
"from",
"stream",
"and",
"compute",
"GPG",
"digest",
"for",
"verification",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/decode.py#L303-L310
|
9,906
|
romanz/trezor-agent
|
libagent/gpg/decode.py
|
remove_armor
|
def remove_armor(armored_data):
"""Decode armored data into its binary form."""
stream = io.BytesIO(armored_data)
lines = stream.readlines()[3:-1]
data = base64.b64decode(b''.join(lines))
payload, checksum = data[:-3], data[-3:]
assert util.crc24(payload) == checksum
return payload
|
python
|
def remove_armor(armored_data):
"""Decode armored data into its binary form."""
stream = io.BytesIO(armored_data)
lines = stream.readlines()[3:-1]
data = base64.b64decode(b''.join(lines))
payload, checksum = data[:-3], data[-3:]
assert util.crc24(payload) == checksum
return payload
|
[
"def",
"remove_armor",
"(",
"armored_data",
")",
":",
"stream",
"=",
"io",
".",
"BytesIO",
"(",
"armored_data",
")",
"lines",
"=",
"stream",
".",
"readlines",
"(",
")",
"[",
"3",
":",
"-",
"1",
"]",
"data",
"=",
"base64",
".",
"b64decode",
"(",
"b''",
".",
"join",
"(",
"lines",
")",
")",
"payload",
",",
"checksum",
"=",
"data",
"[",
":",
"-",
"3",
"]",
",",
"data",
"[",
"-",
"3",
":",
"]",
"assert",
"util",
".",
"crc24",
"(",
"payload",
")",
"==",
"checksum",
"return",
"payload"
] |
Decode armored data into its binary form.
|
[
"Decode",
"armored",
"data",
"into",
"its",
"binary",
"form",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/decode.py#L313-L320
|
9,907
|
romanz/trezor-agent
|
libagent/server.py
|
remove_file
|
def remove_file(path, remove=os.remove, exists=os.path.exists):
"""Remove file, and raise OSError if still exists."""
try:
remove(path)
except OSError:
if exists(path):
raise
|
python
|
def remove_file(path, remove=os.remove, exists=os.path.exists):
"""Remove file, and raise OSError if still exists."""
try:
remove(path)
except OSError:
if exists(path):
raise
|
[
"def",
"remove_file",
"(",
"path",
",",
"remove",
"=",
"os",
".",
"remove",
",",
"exists",
"=",
"os",
".",
"path",
".",
"exists",
")",
":",
"try",
":",
"remove",
"(",
"path",
")",
"except",
"OSError",
":",
"if",
"exists",
"(",
"path",
")",
":",
"raise"
] |
Remove file, and raise OSError if still exists.
|
[
"Remove",
"file",
"and",
"raise",
"OSError",
"if",
"still",
"exists",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/server.py#L14-L20
|
9,908
|
romanz/trezor-agent
|
libagent/server.py
|
unix_domain_socket_server
|
def unix_domain_socket_server(sock_path):
"""
Create UNIX-domain socket on specified path.
Listen on it, and delete it after the generated context is over.
"""
log.debug('serving on %s', sock_path)
remove_file(sock_path)
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind(sock_path)
server.listen(1)
try:
yield server
finally:
remove_file(sock_path)
|
python
|
def unix_domain_socket_server(sock_path):
"""
Create UNIX-domain socket on specified path.
Listen on it, and delete it after the generated context is over.
"""
log.debug('serving on %s', sock_path)
remove_file(sock_path)
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind(sock_path)
server.listen(1)
try:
yield server
finally:
remove_file(sock_path)
|
[
"def",
"unix_domain_socket_server",
"(",
"sock_path",
")",
":",
"log",
".",
"debug",
"(",
"'serving on %s'",
",",
"sock_path",
")",
"remove_file",
"(",
"sock_path",
")",
"server",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_UNIX",
",",
"socket",
".",
"SOCK_STREAM",
")",
"server",
".",
"bind",
"(",
"sock_path",
")",
"server",
".",
"listen",
"(",
"1",
")",
"try",
":",
"yield",
"server",
"finally",
":",
"remove_file",
"(",
"sock_path",
")"
] |
Create UNIX-domain socket on specified path.
Listen on it, and delete it after the generated context is over.
|
[
"Create",
"UNIX",
"-",
"domain",
"socket",
"on",
"specified",
"path",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/server.py#L24-L39
|
9,909
|
romanz/trezor-agent
|
libagent/server.py
|
handle_connection
|
def handle_connection(conn, handler, mutex):
"""
Handle a single connection using the specified protocol handler in a loop.
Since this function may be called concurrently from server_thread,
the specified mutex is used to synchronize the device handling.
Exit when EOFError is raised.
All other exceptions are logged as warnings.
"""
try:
log.debug('welcome agent')
with contextlib.closing(conn):
while True:
msg = util.read_frame(conn)
with mutex:
reply = handler.handle(msg=msg)
util.send(conn, reply)
except EOFError:
log.debug('goodbye agent')
except Exception as e: # pylint: disable=broad-except
log.warning('error: %s', e, exc_info=True)
|
python
|
def handle_connection(conn, handler, mutex):
"""
Handle a single connection using the specified protocol handler in a loop.
Since this function may be called concurrently from server_thread,
the specified mutex is used to synchronize the device handling.
Exit when EOFError is raised.
All other exceptions are logged as warnings.
"""
try:
log.debug('welcome agent')
with contextlib.closing(conn):
while True:
msg = util.read_frame(conn)
with mutex:
reply = handler.handle(msg=msg)
util.send(conn, reply)
except EOFError:
log.debug('goodbye agent')
except Exception as e: # pylint: disable=broad-except
log.warning('error: %s', e, exc_info=True)
|
[
"def",
"handle_connection",
"(",
"conn",
",",
"handler",
",",
"mutex",
")",
":",
"try",
":",
"log",
".",
"debug",
"(",
"'welcome agent'",
")",
"with",
"contextlib",
".",
"closing",
"(",
"conn",
")",
":",
"while",
"True",
":",
"msg",
"=",
"util",
".",
"read_frame",
"(",
"conn",
")",
"with",
"mutex",
":",
"reply",
"=",
"handler",
".",
"handle",
"(",
"msg",
"=",
"msg",
")",
"util",
".",
"send",
"(",
"conn",
",",
"reply",
")",
"except",
"EOFError",
":",
"log",
".",
"debug",
"(",
"'goodbye agent'",
")",
"except",
"Exception",
"as",
"e",
":",
"# pylint: disable=broad-except",
"log",
".",
"warning",
"(",
"'error: %s'",
",",
"e",
",",
"exc_info",
"=",
"True",
")"
] |
Handle a single connection using the specified protocol handler in a loop.
Since this function may be called concurrently from server_thread,
the specified mutex is used to synchronize the device handling.
Exit when EOFError is raised.
All other exceptions are logged as warnings.
|
[
"Handle",
"a",
"single",
"connection",
"using",
"the",
"specified",
"protocol",
"handler",
"in",
"a",
"loop",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/server.py#L79-L100
|
9,910
|
romanz/trezor-agent
|
libagent/server.py
|
retry
|
def retry(func, exception_type, quit_event):
"""
Run the function, retrying when the specified exception_type occurs.
Poll quit_event on each iteration, to be responsive to an external
exit request.
"""
while True:
if quit_event.is_set():
raise StopIteration
try:
return func()
except exception_type:
pass
|
python
|
def retry(func, exception_type, quit_event):
"""
Run the function, retrying when the specified exception_type occurs.
Poll quit_event on each iteration, to be responsive to an external
exit request.
"""
while True:
if quit_event.is_set():
raise StopIteration
try:
return func()
except exception_type:
pass
|
[
"def",
"retry",
"(",
"func",
",",
"exception_type",
",",
"quit_event",
")",
":",
"while",
"True",
":",
"if",
"quit_event",
".",
"is_set",
"(",
")",
":",
"raise",
"StopIteration",
"try",
":",
"return",
"func",
"(",
")",
"except",
"exception_type",
":",
"pass"
] |
Run the function, retrying when the specified exception_type occurs.
Poll quit_event on each iteration, to be responsive to an external
exit request.
|
[
"Run",
"the",
"function",
"retrying",
"when",
"the",
"specified",
"exception_type",
"occurs",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/server.py#L103-L116
|
9,911
|
romanz/trezor-agent
|
libagent/server.py
|
spawn
|
def spawn(func, kwargs):
"""Spawn a thread, and join it after the context is over."""
t = threading.Thread(target=func, kwargs=kwargs)
t.start()
yield
t.join()
|
python
|
def spawn(func, kwargs):
"""Spawn a thread, and join it after the context is over."""
t = threading.Thread(target=func, kwargs=kwargs)
t.start()
yield
t.join()
|
[
"def",
"spawn",
"(",
"func",
",",
"kwargs",
")",
":",
"t",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"func",
",",
"kwargs",
"=",
"kwargs",
")",
"t",
".",
"start",
"(",
")",
"yield",
"t",
".",
"join",
"(",
")"
] |
Spawn a thread, and join it after the context is over.
|
[
"Spawn",
"a",
"thread",
"and",
"join",
"it",
"after",
"the",
"context",
"is",
"over",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/server.py#L142-L147
|
9,912
|
romanz/trezor-agent
|
libagent/server.py
|
run_process
|
def run_process(command, environ):
"""
Run the specified process and wait until it finishes.
Use environ dict for environment variables.
"""
log.info('running %r with %r', command, environ)
env = dict(os.environ)
env.update(environ)
try:
p = subprocess.Popen(args=command, env=env)
except OSError as e:
raise OSError('cannot run %r: %s' % (command, e))
log.debug('subprocess %d is running', p.pid)
ret = p.wait()
log.debug('subprocess %d exited: %d', p.pid, ret)
return ret
|
python
|
def run_process(command, environ):
"""
Run the specified process and wait until it finishes.
Use environ dict for environment variables.
"""
log.info('running %r with %r', command, environ)
env = dict(os.environ)
env.update(environ)
try:
p = subprocess.Popen(args=command, env=env)
except OSError as e:
raise OSError('cannot run %r: %s' % (command, e))
log.debug('subprocess %d is running', p.pid)
ret = p.wait()
log.debug('subprocess %d exited: %d', p.pid, ret)
return ret
|
[
"def",
"run_process",
"(",
"command",
",",
"environ",
")",
":",
"log",
".",
"info",
"(",
"'running %r with %r'",
",",
"command",
",",
"environ",
")",
"env",
"=",
"dict",
"(",
"os",
".",
"environ",
")",
"env",
".",
"update",
"(",
"environ",
")",
"try",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
"=",
"command",
",",
"env",
"=",
"env",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"OSError",
"(",
"'cannot run %r: %s'",
"%",
"(",
"command",
",",
"e",
")",
")",
"log",
".",
"debug",
"(",
"'subprocess %d is running'",
",",
"p",
".",
"pid",
")",
"ret",
"=",
"p",
".",
"wait",
"(",
")",
"log",
".",
"debug",
"(",
"'subprocess %d exited: %d'",
",",
"p",
".",
"pid",
",",
"ret",
")",
"return",
"ret"
] |
Run the specified process and wait until it finishes.
Use environ dict for environment variables.
|
[
"Run",
"the",
"specified",
"process",
"and",
"wait",
"until",
"it",
"finishes",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/server.py#L150-L166
|
9,913
|
romanz/trezor-agent
|
libagent/gpg/keyring.py
|
check_output
|
def check_output(args, env=None, sp=subprocess):
"""Call an external binary and return its stdout."""
log.debug('calling %s with env %s', args, env)
output = sp.check_output(args=args, env=env)
log.debug('output: %r', output)
return output
|
python
|
def check_output(args, env=None, sp=subprocess):
"""Call an external binary and return its stdout."""
log.debug('calling %s with env %s', args, env)
output = sp.check_output(args=args, env=env)
log.debug('output: %r', output)
return output
|
[
"def",
"check_output",
"(",
"args",
",",
"env",
"=",
"None",
",",
"sp",
"=",
"subprocess",
")",
":",
"log",
".",
"debug",
"(",
"'calling %s with env %s'",
",",
"args",
",",
"env",
")",
"output",
"=",
"sp",
".",
"check_output",
"(",
"args",
"=",
"args",
",",
"env",
"=",
"env",
")",
"log",
".",
"debug",
"(",
"'output: %r'",
",",
"output",
")",
"return",
"output"
] |
Call an external binary and return its stdout.
|
[
"Call",
"an",
"external",
"binary",
"and",
"return",
"its",
"stdout",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L17-L22
|
9,914
|
romanz/trezor-agent
|
libagent/gpg/keyring.py
|
get_agent_sock_path
|
def get_agent_sock_path(env=None, sp=subprocess):
"""Parse gpgconf output to find out GPG agent UNIX socket path."""
args = [util.which('gpgconf'), '--list-dirs']
output = check_output(args=args, env=env, sp=sp)
lines = output.strip().split(b'\n')
dirs = dict(line.split(b':', 1) for line in lines)
log.debug('%s: %s', args, dirs)
return dirs[b'agent-socket']
|
python
|
def get_agent_sock_path(env=None, sp=subprocess):
"""Parse gpgconf output to find out GPG agent UNIX socket path."""
args = [util.which('gpgconf'), '--list-dirs']
output = check_output(args=args, env=env, sp=sp)
lines = output.strip().split(b'\n')
dirs = dict(line.split(b':', 1) for line in lines)
log.debug('%s: %s', args, dirs)
return dirs[b'agent-socket']
|
[
"def",
"get_agent_sock_path",
"(",
"env",
"=",
"None",
",",
"sp",
"=",
"subprocess",
")",
":",
"args",
"=",
"[",
"util",
".",
"which",
"(",
"'gpgconf'",
")",
",",
"'--list-dirs'",
"]",
"output",
"=",
"check_output",
"(",
"args",
"=",
"args",
",",
"env",
"=",
"env",
",",
"sp",
"=",
"sp",
")",
"lines",
"=",
"output",
".",
"strip",
"(",
")",
".",
"split",
"(",
"b'\\n'",
")",
"dirs",
"=",
"dict",
"(",
"line",
".",
"split",
"(",
"b':'",
",",
"1",
")",
"for",
"line",
"in",
"lines",
")",
"log",
".",
"debug",
"(",
"'%s: %s'",
",",
"args",
",",
"dirs",
")",
"return",
"dirs",
"[",
"b'agent-socket'",
"]"
] |
Parse gpgconf output to find out GPG agent UNIX socket path.
|
[
"Parse",
"gpgconf",
"output",
"to",
"find",
"out",
"GPG",
"agent",
"UNIX",
"socket",
"path",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L25-L32
|
9,915
|
romanz/trezor-agent
|
libagent/gpg/keyring.py
|
connect_to_agent
|
def connect_to_agent(env=None, sp=subprocess):
"""Connect to GPG agent's UNIX socket."""
sock_path = get_agent_sock_path(sp=sp, env=env)
# Make sure the original gpg-agent is running.
check_output(args=['gpg-connect-agent', '/bye'], sp=sp)
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(sock_path)
return sock
|
python
|
def connect_to_agent(env=None, sp=subprocess):
"""Connect to GPG agent's UNIX socket."""
sock_path = get_agent_sock_path(sp=sp, env=env)
# Make sure the original gpg-agent is running.
check_output(args=['gpg-connect-agent', '/bye'], sp=sp)
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(sock_path)
return sock
|
[
"def",
"connect_to_agent",
"(",
"env",
"=",
"None",
",",
"sp",
"=",
"subprocess",
")",
":",
"sock_path",
"=",
"get_agent_sock_path",
"(",
"sp",
"=",
"sp",
",",
"env",
"=",
"env",
")",
"# Make sure the original gpg-agent is running.",
"check_output",
"(",
"args",
"=",
"[",
"'gpg-connect-agent'",
",",
"'/bye'",
"]",
",",
"sp",
"=",
"sp",
")",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_UNIX",
",",
"socket",
".",
"SOCK_STREAM",
")",
"sock",
".",
"connect",
"(",
"sock_path",
")",
"return",
"sock"
] |
Connect to GPG agent's UNIX socket.
|
[
"Connect",
"to",
"GPG",
"agent",
"s",
"UNIX",
"socket",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L35-L42
|
9,916
|
romanz/trezor-agent
|
libagent/gpg/keyring.py
|
sendline
|
def sendline(sock, msg, confidential=False):
"""Send a binary message, followed by EOL."""
log.debug('<- %r', ('<snip>' if confidential else msg))
sock.sendall(msg + b'\n')
|
python
|
def sendline(sock, msg, confidential=False):
"""Send a binary message, followed by EOL."""
log.debug('<- %r', ('<snip>' if confidential else msg))
sock.sendall(msg + b'\n')
|
[
"def",
"sendline",
"(",
"sock",
",",
"msg",
",",
"confidential",
"=",
"False",
")",
":",
"log",
".",
"debug",
"(",
"'<- %r'",
",",
"(",
"'<snip>'",
"if",
"confidential",
"else",
"msg",
")",
")",
"sock",
".",
"sendall",
"(",
"msg",
"+",
"b'\\n'",
")"
] |
Send a binary message, followed by EOL.
|
[
"Send",
"a",
"binary",
"message",
"followed",
"by",
"EOL",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L51-L54
|
9,917
|
romanz/trezor-agent
|
libagent/gpg/keyring.py
|
recvline
|
def recvline(sock):
"""Receive a single line from the socket."""
reply = io.BytesIO()
while True:
c = sock.recv(1)
if not c:
return None # socket is closed
if c == b'\n':
break
reply.write(c)
result = reply.getvalue()
log.debug('-> %r', result)
return result
|
python
|
def recvline(sock):
"""Receive a single line from the socket."""
reply = io.BytesIO()
while True:
c = sock.recv(1)
if not c:
return None # socket is closed
if c == b'\n':
break
reply.write(c)
result = reply.getvalue()
log.debug('-> %r', result)
return result
|
[
"def",
"recvline",
"(",
"sock",
")",
":",
"reply",
"=",
"io",
".",
"BytesIO",
"(",
")",
"while",
"True",
":",
"c",
"=",
"sock",
".",
"recv",
"(",
"1",
")",
"if",
"not",
"c",
":",
"return",
"None",
"# socket is closed",
"if",
"c",
"==",
"b'\\n'",
":",
"break",
"reply",
".",
"write",
"(",
"c",
")",
"result",
"=",
"reply",
".",
"getvalue",
"(",
")",
"log",
".",
"debug",
"(",
"'-> %r'",
",",
"result",
")",
"return",
"result"
] |
Receive a single line from the socket.
|
[
"Receive",
"a",
"single",
"line",
"from",
"the",
"socket",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L57-L72
|
9,918
|
romanz/trezor-agent
|
libagent/gpg/keyring.py
|
parse_term
|
def parse_term(s):
"""Parse single s-expr term from bytes."""
size, s = s.split(b':', 1)
size = int(size)
return s[:size], s[size:]
|
python
|
def parse_term(s):
"""Parse single s-expr term from bytes."""
size, s = s.split(b':', 1)
size = int(size)
return s[:size], s[size:]
|
[
"def",
"parse_term",
"(",
"s",
")",
":",
"size",
",",
"s",
"=",
"s",
".",
"split",
"(",
"b':'",
",",
"1",
")",
"size",
"=",
"int",
"(",
"size",
")",
"return",
"s",
"[",
":",
"size",
"]",
",",
"s",
"[",
"size",
":",
"]"
] |
Parse single s-expr term from bytes.
|
[
"Parse",
"single",
"s",
"-",
"expr",
"term",
"from",
"bytes",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L97-L101
|
9,919
|
romanz/trezor-agent
|
libagent/gpg/keyring.py
|
parse
|
def parse(s):
"""Parse full s-expr from bytes."""
if s.startswith(b'('):
s = s[1:]
name, s = parse_term(s)
values = [name]
while not s.startswith(b')'):
value, s = parse(s)
values.append(value)
return values, s[1:]
return parse_term(s)
|
python
|
def parse(s):
"""Parse full s-expr from bytes."""
if s.startswith(b'('):
s = s[1:]
name, s = parse_term(s)
values = [name]
while not s.startswith(b')'):
value, s = parse(s)
values.append(value)
return values, s[1:]
return parse_term(s)
|
[
"def",
"parse",
"(",
"s",
")",
":",
"if",
"s",
".",
"startswith",
"(",
"b'('",
")",
":",
"s",
"=",
"s",
"[",
"1",
":",
"]",
"name",
",",
"s",
"=",
"parse_term",
"(",
"s",
")",
"values",
"=",
"[",
"name",
"]",
"while",
"not",
"s",
".",
"startswith",
"(",
"b')'",
")",
":",
"value",
",",
"s",
"=",
"parse",
"(",
"s",
")",
"values",
".",
"append",
"(",
"value",
")",
"return",
"values",
",",
"s",
"[",
"1",
":",
"]",
"return",
"parse_term",
"(",
"s",
")"
] |
Parse full s-expr from bytes.
|
[
"Parse",
"full",
"s",
"-",
"expr",
"from",
"bytes",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L104-L115
|
9,920
|
romanz/trezor-agent
|
libagent/gpg/keyring.py
|
parse_sig
|
def parse_sig(sig):
"""Parse signature integer values from s-expr."""
label, sig = sig
assert label == b'sig-val'
algo_name = sig[0]
parser = {b'rsa': _parse_rsa_sig,
b'ecdsa': _parse_ecdsa_sig,
b'eddsa': _parse_eddsa_sig,
b'dsa': _parse_dsa_sig}[algo_name]
return parser(args=sig[1:])
|
python
|
def parse_sig(sig):
"""Parse signature integer values from s-expr."""
label, sig = sig
assert label == b'sig-val'
algo_name = sig[0]
parser = {b'rsa': _parse_rsa_sig,
b'ecdsa': _parse_ecdsa_sig,
b'eddsa': _parse_eddsa_sig,
b'dsa': _parse_dsa_sig}[algo_name]
return parser(args=sig[1:])
|
[
"def",
"parse_sig",
"(",
"sig",
")",
":",
"label",
",",
"sig",
"=",
"sig",
"assert",
"label",
"==",
"b'sig-val'",
"algo_name",
"=",
"sig",
"[",
"0",
"]",
"parser",
"=",
"{",
"b'rsa'",
":",
"_parse_rsa_sig",
",",
"b'ecdsa'",
":",
"_parse_ecdsa_sig",
",",
"b'eddsa'",
":",
"_parse_eddsa_sig",
",",
"b'dsa'",
":",
"_parse_dsa_sig",
"}",
"[",
"algo_name",
"]",
"return",
"parser",
"(",
"args",
"=",
"sig",
"[",
"1",
":",
"]",
")"
] |
Parse signature integer values from s-expr.
|
[
"Parse",
"signature",
"integer",
"values",
"from",
"s",
"-",
"expr",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L137-L146
|
9,921
|
romanz/trezor-agent
|
libagent/gpg/keyring.py
|
sign_digest
|
def sign_digest(sock, keygrip, digest, sp=subprocess, environ=None):
"""Sign a digest using specified key using GPG agent."""
hash_algo = 8 # SHA256
assert len(digest) == 32
assert communicate(sock, 'RESET').startswith(b'OK')
ttyname = check_output(args=['tty'], sp=sp).strip()
options = ['ttyname={}'.format(ttyname)] # set TTY for passphrase entry
display = (environ or os.environ).get('DISPLAY')
if display is not None:
options.append('display={}'.format(display))
for opt in options:
assert communicate(sock, 'OPTION {}'.format(opt)) == b'OK'
assert communicate(sock, 'SIGKEY {}'.format(keygrip)) == b'OK'
hex_digest = binascii.hexlify(digest).upper().decode('ascii')
assert communicate(sock, 'SETHASH {} {}'.format(hash_algo,
hex_digest)) == b'OK'
assert communicate(sock, 'SETKEYDESC '
'Sign+a+new+TREZOR-based+subkey') == b'OK'
assert communicate(sock, 'PKSIGN') == b'OK'
while True:
line = recvline(sock).strip()
if line.startswith(b'S PROGRESS'):
continue
else:
break
line = unescape(line)
log.debug('unescaped: %r', line)
prefix, sig = line.split(b' ', 1)
if prefix != b'D':
raise ValueError(prefix)
sig, leftover = parse(sig)
assert not leftover, leftover
return parse_sig(sig)
|
python
|
def sign_digest(sock, keygrip, digest, sp=subprocess, environ=None):
"""Sign a digest using specified key using GPG agent."""
hash_algo = 8 # SHA256
assert len(digest) == 32
assert communicate(sock, 'RESET').startswith(b'OK')
ttyname = check_output(args=['tty'], sp=sp).strip()
options = ['ttyname={}'.format(ttyname)] # set TTY for passphrase entry
display = (environ or os.environ).get('DISPLAY')
if display is not None:
options.append('display={}'.format(display))
for opt in options:
assert communicate(sock, 'OPTION {}'.format(opt)) == b'OK'
assert communicate(sock, 'SIGKEY {}'.format(keygrip)) == b'OK'
hex_digest = binascii.hexlify(digest).upper().decode('ascii')
assert communicate(sock, 'SETHASH {} {}'.format(hash_algo,
hex_digest)) == b'OK'
assert communicate(sock, 'SETKEYDESC '
'Sign+a+new+TREZOR-based+subkey') == b'OK'
assert communicate(sock, 'PKSIGN') == b'OK'
while True:
line = recvline(sock).strip()
if line.startswith(b'S PROGRESS'):
continue
else:
break
line = unescape(line)
log.debug('unescaped: %r', line)
prefix, sig = line.split(b' ', 1)
if prefix != b'D':
raise ValueError(prefix)
sig, leftover = parse(sig)
assert not leftover, leftover
return parse_sig(sig)
|
[
"def",
"sign_digest",
"(",
"sock",
",",
"keygrip",
",",
"digest",
",",
"sp",
"=",
"subprocess",
",",
"environ",
"=",
"None",
")",
":",
"hash_algo",
"=",
"8",
"# SHA256",
"assert",
"len",
"(",
"digest",
")",
"==",
"32",
"assert",
"communicate",
"(",
"sock",
",",
"'RESET'",
")",
".",
"startswith",
"(",
"b'OK'",
")",
"ttyname",
"=",
"check_output",
"(",
"args",
"=",
"[",
"'tty'",
"]",
",",
"sp",
"=",
"sp",
")",
".",
"strip",
"(",
")",
"options",
"=",
"[",
"'ttyname={}'",
".",
"format",
"(",
"ttyname",
")",
"]",
"# set TTY for passphrase entry",
"display",
"=",
"(",
"environ",
"or",
"os",
".",
"environ",
")",
".",
"get",
"(",
"'DISPLAY'",
")",
"if",
"display",
"is",
"not",
"None",
":",
"options",
".",
"append",
"(",
"'display={}'",
".",
"format",
"(",
"display",
")",
")",
"for",
"opt",
"in",
"options",
":",
"assert",
"communicate",
"(",
"sock",
",",
"'OPTION {}'",
".",
"format",
"(",
"opt",
")",
")",
"==",
"b'OK'",
"assert",
"communicate",
"(",
"sock",
",",
"'SIGKEY {}'",
".",
"format",
"(",
"keygrip",
")",
")",
"==",
"b'OK'",
"hex_digest",
"=",
"binascii",
".",
"hexlify",
"(",
"digest",
")",
".",
"upper",
"(",
")",
".",
"decode",
"(",
"'ascii'",
")",
"assert",
"communicate",
"(",
"sock",
",",
"'SETHASH {} {}'",
".",
"format",
"(",
"hash_algo",
",",
"hex_digest",
")",
")",
"==",
"b'OK'",
"assert",
"communicate",
"(",
"sock",
",",
"'SETKEYDESC '",
"'Sign+a+new+TREZOR-based+subkey'",
")",
"==",
"b'OK'",
"assert",
"communicate",
"(",
"sock",
",",
"'PKSIGN'",
")",
"==",
"b'OK'",
"while",
"True",
":",
"line",
"=",
"recvline",
"(",
"sock",
")",
".",
"strip",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"b'S PROGRESS'",
")",
":",
"continue",
"else",
":",
"break",
"line",
"=",
"unescape",
"(",
"line",
")",
"log",
".",
"debug",
"(",
"'unescaped: %r'",
",",
"line",
")",
"prefix",
",",
"sig",
"=",
"line",
".",
"split",
"(",
"b' '",
",",
"1",
")",
"if",
"prefix",
"!=",
"b'D'",
":",
"raise",
"ValueError",
"(",
"prefix",
")",
"sig",
",",
"leftover",
"=",
"parse",
"(",
"sig",
")",
"assert",
"not",
"leftover",
",",
"leftover",
"return",
"parse_sig",
"(",
"sig",
")"
] |
Sign a digest using specified key using GPG agent.
|
[
"Sign",
"a",
"digest",
"using",
"specified",
"key",
"using",
"GPG",
"agent",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L149-L188
|
9,922
|
romanz/trezor-agent
|
libagent/gpg/keyring.py
|
get_gnupg_components
|
def get_gnupg_components(sp=subprocess):
"""Parse GnuPG components' paths."""
args = [util.which('gpgconf'), '--list-components']
output = check_output(args=args, sp=sp)
components = dict(re.findall('(.*):.*:(.*)', output.decode('utf-8')))
log.debug('gpgconf --list-components: %s', components)
return components
|
python
|
def get_gnupg_components(sp=subprocess):
"""Parse GnuPG components' paths."""
args = [util.which('gpgconf'), '--list-components']
output = check_output(args=args, sp=sp)
components = dict(re.findall('(.*):.*:(.*)', output.decode('utf-8')))
log.debug('gpgconf --list-components: %s', components)
return components
|
[
"def",
"get_gnupg_components",
"(",
"sp",
"=",
"subprocess",
")",
":",
"args",
"=",
"[",
"util",
".",
"which",
"(",
"'gpgconf'",
")",
",",
"'--list-components'",
"]",
"output",
"=",
"check_output",
"(",
"args",
"=",
"args",
",",
"sp",
"=",
"sp",
")",
"components",
"=",
"dict",
"(",
"re",
".",
"findall",
"(",
"'(.*):.*:(.*)'",
",",
"output",
".",
"decode",
"(",
"'utf-8'",
")",
")",
")",
"log",
".",
"debug",
"(",
"'gpgconf --list-components: %s'",
",",
"components",
")",
"return",
"components"
] |
Parse GnuPG components' paths.
|
[
"Parse",
"GnuPG",
"components",
"paths",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L191-L197
|
9,923
|
romanz/trezor-agent
|
libagent/gpg/keyring.py
|
gpg_command
|
def gpg_command(args, env=None):
"""Prepare common GPG command line arguments."""
if env is None:
env = os.environ
cmd = get_gnupg_binary(neopg_binary=env.get('NEOPG_BINARY'))
return [cmd] + args
|
python
|
def gpg_command(args, env=None):
"""Prepare common GPG command line arguments."""
if env is None:
env = os.environ
cmd = get_gnupg_binary(neopg_binary=env.get('NEOPG_BINARY'))
return [cmd] + args
|
[
"def",
"gpg_command",
"(",
"args",
",",
"env",
"=",
"None",
")",
":",
"if",
"env",
"is",
"None",
":",
"env",
"=",
"os",
".",
"environ",
"cmd",
"=",
"get_gnupg_binary",
"(",
"neopg_binary",
"=",
"env",
".",
"get",
"(",
"'NEOPG_BINARY'",
")",
")",
"return",
"[",
"cmd",
"]",
"+",
"args"
] |
Prepare common GPG command line arguments.
|
[
"Prepare",
"common",
"GPG",
"command",
"line",
"arguments",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L208-L213
|
9,924
|
romanz/trezor-agent
|
libagent/gpg/keyring.py
|
export_public_key
|
def export_public_key(user_id, env=None, sp=subprocess):
"""Export GPG public key for specified `user_id`."""
args = gpg_command(['--export', user_id])
result = check_output(args=args, env=env, sp=sp)
if not result:
log.error('could not find public key %r in local GPG keyring', user_id)
raise KeyError(user_id)
return result
|
python
|
def export_public_key(user_id, env=None, sp=subprocess):
"""Export GPG public key for specified `user_id`."""
args = gpg_command(['--export', user_id])
result = check_output(args=args, env=env, sp=sp)
if not result:
log.error('could not find public key %r in local GPG keyring', user_id)
raise KeyError(user_id)
return result
|
[
"def",
"export_public_key",
"(",
"user_id",
",",
"env",
"=",
"None",
",",
"sp",
"=",
"subprocess",
")",
":",
"args",
"=",
"gpg_command",
"(",
"[",
"'--export'",
",",
"user_id",
"]",
")",
"result",
"=",
"check_output",
"(",
"args",
"=",
"args",
",",
"env",
"=",
"env",
",",
"sp",
"=",
"sp",
")",
"if",
"not",
"result",
":",
"log",
".",
"error",
"(",
"'could not find public key %r in local GPG keyring'",
",",
"user_id",
")",
"raise",
"KeyError",
"(",
"user_id",
")",
"return",
"result"
] |
Export GPG public key for specified `user_id`.
|
[
"Export",
"GPG",
"public",
"key",
"for",
"specified",
"user_id",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L233-L240
|
9,925
|
romanz/trezor-agent
|
libagent/gpg/keyring.py
|
export_public_keys
|
def export_public_keys(env=None, sp=subprocess):
"""Export all GPG public keys."""
args = gpg_command(['--export'])
result = check_output(args=args, env=env, sp=sp)
if not result:
raise KeyError('No GPG public keys found at env: {!r}'.format(env))
return result
|
python
|
def export_public_keys(env=None, sp=subprocess):
"""Export all GPG public keys."""
args = gpg_command(['--export'])
result = check_output(args=args, env=env, sp=sp)
if not result:
raise KeyError('No GPG public keys found at env: {!r}'.format(env))
return result
|
[
"def",
"export_public_keys",
"(",
"env",
"=",
"None",
",",
"sp",
"=",
"subprocess",
")",
":",
"args",
"=",
"gpg_command",
"(",
"[",
"'--export'",
"]",
")",
"result",
"=",
"check_output",
"(",
"args",
"=",
"args",
",",
"env",
"=",
"env",
",",
"sp",
"=",
"sp",
")",
"if",
"not",
"result",
":",
"raise",
"KeyError",
"(",
"'No GPG public keys found at env: {!r}'",
".",
"format",
"(",
"env",
")",
")",
"return",
"result"
] |
Export all GPG public keys.
|
[
"Export",
"all",
"GPG",
"public",
"keys",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L243-L249
|
9,926
|
romanz/trezor-agent
|
libagent/gpg/keyring.py
|
create_agent_signer
|
def create_agent_signer(user_id):
"""Sign digest with existing GPG keys using gpg-agent tool."""
sock = connect_to_agent(env=os.environ)
keygrip = get_keygrip(user_id)
def sign(digest):
"""Sign the digest and return an ECDSA/RSA/DSA signature."""
return sign_digest(sock=sock, keygrip=keygrip, digest=digest)
return sign
|
python
|
def create_agent_signer(user_id):
"""Sign digest with existing GPG keys using gpg-agent tool."""
sock = connect_to_agent(env=os.environ)
keygrip = get_keygrip(user_id)
def sign(digest):
"""Sign the digest and return an ECDSA/RSA/DSA signature."""
return sign_digest(sock=sock, keygrip=keygrip, digest=digest)
return sign
|
[
"def",
"create_agent_signer",
"(",
"user_id",
")",
":",
"sock",
"=",
"connect_to_agent",
"(",
"env",
"=",
"os",
".",
"environ",
")",
"keygrip",
"=",
"get_keygrip",
"(",
"user_id",
")",
"def",
"sign",
"(",
"digest",
")",
":",
"\"\"\"Sign the digest and return an ECDSA/RSA/DSA signature.\"\"\"",
"return",
"sign_digest",
"(",
"sock",
"=",
"sock",
",",
"keygrip",
"=",
"keygrip",
",",
"digest",
"=",
"digest",
")",
"return",
"sign"
] |
Sign digest with existing GPG keys using gpg-agent tool.
|
[
"Sign",
"digest",
"with",
"existing",
"GPG",
"keys",
"using",
"gpg",
"-",
"agent",
"tool",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/keyring.py#L252-L261
|
9,927
|
romanz/trezor-agent
|
libagent/ssh/protocol.py
|
msg_name
|
def msg_name(code):
"""Convert integer message code into a string name."""
ids = {v: k for k, v in COMMANDS.items()}
return ids[code]
|
python
|
def msg_name(code):
"""Convert integer message code into a string name."""
ids = {v: k for k, v in COMMANDS.items()}
return ids[code]
|
[
"def",
"msg_name",
"(",
"code",
")",
":",
"ids",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"COMMANDS",
".",
"items",
"(",
")",
"}",
"return",
"ids",
"[",
"code",
"]"
] |
Convert integer message code into a string name.
|
[
"Convert",
"integer",
"message",
"code",
"into",
"a",
"string",
"name",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/protocol.py#L51-L54
|
9,928
|
romanz/trezor-agent
|
libagent/ssh/protocol.py
|
_legacy_pubs
|
def _legacy_pubs(buf):
"""SSH v1 public keys are not supported."""
leftover = buf.read()
if leftover:
log.warning('skipping leftover: %r', leftover)
code = util.pack('B', msg_code('SSH_AGENT_RSA_IDENTITIES_ANSWER'))
num = util.pack('L', 0) # no SSH v1 keys
return util.frame(code, num)
|
python
|
def _legacy_pubs(buf):
"""SSH v1 public keys are not supported."""
leftover = buf.read()
if leftover:
log.warning('skipping leftover: %r', leftover)
code = util.pack('B', msg_code('SSH_AGENT_RSA_IDENTITIES_ANSWER'))
num = util.pack('L', 0) # no SSH v1 keys
return util.frame(code, num)
|
[
"def",
"_legacy_pubs",
"(",
"buf",
")",
":",
"leftover",
"=",
"buf",
".",
"read",
"(",
")",
"if",
"leftover",
":",
"log",
".",
"warning",
"(",
"'skipping leftover: %r'",
",",
"leftover",
")",
"code",
"=",
"util",
".",
"pack",
"(",
"'B'",
",",
"msg_code",
"(",
"'SSH_AGENT_RSA_IDENTITIES_ANSWER'",
")",
")",
"num",
"=",
"util",
".",
"pack",
"(",
"'L'",
",",
"0",
")",
"# no SSH v1 keys",
"return",
"util",
".",
"frame",
"(",
"code",
",",
"num",
")"
] |
SSH v1 public keys are not supported.
|
[
"SSH",
"v1",
"public",
"keys",
"are",
"not",
"supported",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/protocol.py#L63-L70
|
9,929
|
romanz/trezor-agent
|
libagent/ssh/protocol.py
|
Handler.handle
|
def handle(self, msg):
"""Handle SSH message from the SSH client and return the response."""
debug_msg = ': {!r}'.format(msg) if self.debug else ''
log.debug('request: %d bytes%s', len(msg), debug_msg)
buf = io.BytesIO(msg)
code, = util.recv(buf, '>B')
if code not in self.methods:
log.warning('Unsupported command: %s (%d)', msg_name(code), code)
return failure()
method = self.methods[code]
log.debug('calling %s()', method.__name__)
reply = method(buf=buf)
debug_reply = ': {!r}'.format(reply) if self.debug else ''
log.debug('reply: %d bytes%s', len(reply), debug_reply)
return reply
|
python
|
def handle(self, msg):
"""Handle SSH message from the SSH client and return the response."""
debug_msg = ': {!r}'.format(msg) if self.debug else ''
log.debug('request: %d bytes%s', len(msg), debug_msg)
buf = io.BytesIO(msg)
code, = util.recv(buf, '>B')
if code not in self.methods:
log.warning('Unsupported command: %s (%d)', msg_name(code), code)
return failure()
method = self.methods[code]
log.debug('calling %s()', method.__name__)
reply = method(buf=buf)
debug_reply = ': {!r}'.format(reply) if self.debug else ''
log.debug('reply: %d bytes%s', len(reply), debug_reply)
return reply
|
[
"def",
"handle",
"(",
"self",
",",
"msg",
")",
":",
"debug_msg",
"=",
"': {!r}'",
".",
"format",
"(",
"msg",
")",
"if",
"self",
".",
"debug",
"else",
"''",
"log",
".",
"debug",
"(",
"'request: %d bytes%s'",
",",
"len",
"(",
"msg",
")",
",",
"debug_msg",
")",
"buf",
"=",
"io",
".",
"BytesIO",
"(",
"msg",
")",
"code",
",",
"=",
"util",
".",
"recv",
"(",
"buf",
",",
"'>B'",
")",
"if",
"code",
"not",
"in",
"self",
".",
"methods",
":",
"log",
".",
"warning",
"(",
"'Unsupported command: %s (%d)'",
",",
"msg_name",
"(",
"code",
")",
",",
"code",
")",
"return",
"failure",
"(",
")",
"method",
"=",
"self",
".",
"methods",
"[",
"code",
"]",
"log",
".",
"debug",
"(",
"'calling %s()'",
",",
"method",
".",
"__name__",
")",
"reply",
"=",
"method",
"(",
"buf",
"=",
"buf",
")",
"debug_reply",
"=",
"': {!r}'",
".",
"format",
"(",
"reply",
")",
"if",
"self",
".",
"debug",
"else",
"''",
"log",
".",
"debug",
"(",
"'reply: %d bytes%s'",
",",
"len",
"(",
"reply",
")",
",",
"debug_reply",
")",
"return",
"reply"
] |
Handle SSH message from the SSH client and return the response.
|
[
"Handle",
"SSH",
"message",
"from",
"the",
"SSH",
"client",
"and",
"return",
"the",
"response",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/protocol.py#L91-L106
|
9,930
|
romanz/trezor-agent
|
libagent/ssh/protocol.py
|
Handler.list_pubs
|
def list_pubs(self, buf):
"""SSH v2 public keys are serialized and returned."""
assert not buf.read()
keys = self.conn.parse_public_keys()
code = util.pack('B', msg_code('SSH2_AGENT_IDENTITIES_ANSWER'))
num = util.pack('L', len(keys))
log.debug('available keys: %s', [k['name'] for k in keys])
for i, k in enumerate(keys):
log.debug('%2d) %s', i+1, k['fingerprint'])
pubs = [util.frame(k['blob']) + util.frame(k['name']) for k in keys]
return util.frame(code, num, *pubs)
|
python
|
def list_pubs(self, buf):
"""SSH v2 public keys are serialized and returned."""
assert not buf.read()
keys = self.conn.parse_public_keys()
code = util.pack('B', msg_code('SSH2_AGENT_IDENTITIES_ANSWER'))
num = util.pack('L', len(keys))
log.debug('available keys: %s', [k['name'] for k in keys])
for i, k in enumerate(keys):
log.debug('%2d) %s', i+1, k['fingerprint'])
pubs = [util.frame(k['blob']) + util.frame(k['name']) for k in keys]
return util.frame(code, num, *pubs)
|
[
"def",
"list_pubs",
"(",
"self",
",",
"buf",
")",
":",
"assert",
"not",
"buf",
".",
"read",
"(",
")",
"keys",
"=",
"self",
".",
"conn",
".",
"parse_public_keys",
"(",
")",
"code",
"=",
"util",
".",
"pack",
"(",
"'B'",
",",
"msg_code",
"(",
"'SSH2_AGENT_IDENTITIES_ANSWER'",
")",
")",
"num",
"=",
"util",
".",
"pack",
"(",
"'L'",
",",
"len",
"(",
"keys",
")",
")",
"log",
".",
"debug",
"(",
"'available keys: %s'",
",",
"[",
"k",
"[",
"'name'",
"]",
"for",
"k",
"in",
"keys",
"]",
")",
"for",
"i",
",",
"k",
"in",
"enumerate",
"(",
"keys",
")",
":",
"log",
".",
"debug",
"(",
"'%2d) %s'",
",",
"i",
"+",
"1",
",",
"k",
"[",
"'fingerprint'",
"]",
")",
"pubs",
"=",
"[",
"util",
".",
"frame",
"(",
"k",
"[",
"'blob'",
"]",
")",
"+",
"util",
".",
"frame",
"(",
"k",
"[",
"'name'",
"]",
")",
"for",
"k",
"in",
"keys",
"]",
"return",
"util",
".",
"frame",
"(",
"code",
",",
"num",
",",
"*",
"pubs",
")"
] |
SSH v2 public keys are serialized and returned.
|
[
"SSH",
"v2",
"public",
"keys",
"are",
"serialized",
"and",
"returned",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/protocol.py#L108-L118
|
9,931
|
romanz/trezor-agent
|
libagent/ssh/protocol.py
|
Handler.sign_message
|
def sign_message(self, buf):
"""
SSH v2 public key authentication is performed.
If the required key is not supported, raise KeyError
If the signature is invalid, raise ValueError
"""
key = formats.parse_pubkey(util.read_frame(buf))
log.debug('looking for %s', key['fingerprint'])
blob = util.read_frame(buf)
assert util.read_frame(buf) == b''
assert not buf.read()
for k in self.conn.parse_public_keys():
if (k['fingerprint']) == (key['fingerprint']):
log.debug('using key %r (%s)', k['name'], k['fingerprint'])
key = k
break
else:
raise KeyError('key not found')
label = key['name'].decode('utf-8')
log.debug('signing %d-byte blob with "%s" key', len(blob), label)
try:
signature = self.conn.sign(blob=blob, identity=key['identity'])
except IOError:
return failure()
log.debug('signature: %r', signature)
try:
sig_bytes = key['verifier'](sig=signature, msg=blob)
log.info('signature status: OK')
except formats.ecdsa.BadSignatureError:
log.exception('signature status: ERROR')
raise ValueError('invalid ECDSA signature')
log.debug('signature size: %d bytes', len(sig_bytes))
data = util.frame(util.frame(key['type']), util.frame(sig_bytes))
code = util.pack('B', msg_code('SSH2_AGENT_SIGN_RESPONSE'))
return util.frame(code, data)
|
python
|
def sign_message(self, buf):
"""
SSH v2 public key authentication is performed.
If the required key is not supported, raise KeyError
If the signature is invalid, raise ValueError
"""
key = formats.parse_pubkey(util.read_frame(buf))
log.debug('looking for %s', key['fingerprint'])
blob = util.read_frame(buf)
assert util.read_frame(buf) == b''
assert not buf.read()
for k in self.conn.parse_public_keys():
if (k['fingerprint']) == (key['fingerprint']):
log.debug('using key %r (%s)', k['name'], k['fingerprint'])
key = k
break
else:
raise KeyError('key not found')
label = key['name'].decode('utf-8')
log.debug('signing %d-byte blob with "%s" key', len(blob), label)
try:
signature = self.conn.sign(blob=blob, identity=key['identity'])
except IOError:
return failure()
log.debug('signature: %r', signature)
try:
sig_bytes = key['verifier'](sig=signature, msg=blob)
log.info('signature status: OK')
except formats.ecdsa.BadSignatureError:
log.exception('signature status: ERROR')
raise ValueError('invalid ECDSA signature')
log.debug('signature size: %d bytes', len(sig_bytes))
data = util.frame(util.frame(key['type']), util.frame(sig_bytes))
code = util.pack('B', msg_code('SSH2_AGENT_SIGN_RESPONSE'))
return util.frame(code, data)
|
[
"def",
"sign_message",
"(",
"self",
",",
"buf",
")",
":",
"key",
"=",
"formats",
".",
"parse_pubkey",
"(",
"util",
".",
"read_frame",
"(",
"buf",
")",
")",
"log",
".",
"debug",
"(",
"'looking for %s'",
",",
"key",
"[",
"'fingerprint'",
"]",
")",
"blob",
"=",
"util",
".",
"read_frame",
"(",
"buf",
")",
"assert",
"util",
".",
"read_frame",
"(",
"buf",
")",
"==",
"b''",
"assert",
"not",
"buf",
".",
"read",
"(",
")",
"for",
"k",
"in",
"self",
".",
"conn",
".",
"parse_public_keys",
"(",
")",
":",
"if",
"(",
"k",
"[",
"'fingerprint'",
"]",
")",
"==",
"(",
"key",
"[",
"'fingerprint'",
"]",
")",
":",
"log",
".",
"debug",
"(",
"'using key %r (%s)'",
",",
"k",
"[",
"'name'",
"]",
",",
"k",
"[",
"'fingerprint'",
"]",
")",
"key",
"=",
"k",
"break",
"else",
":",
"raise",
"KeyError",
"(",
"'key not found'",
")",
"label",
"=",
"key",
"[",
"'name'",
"]",
".",
"decode",
"(",
"'utf-8'",
")",
"log",
".",
"debug",
"(",
"'signing %d-byte blob with \"%s\" key'",
",",
"len",
"(",
"blob",
")",
",",
"label",
")",
"try",
":",
"signature",
"=",
"self",
".",
"conn",
".",
"sign",
"(",
"blob",
"=",
"blob",
",",
"identity",
"=",
"key",
"[",
"'identity'",
"]",
")",
"except",
"IOError",
":",
"return",
"failure",
"(",
")",
"log",
".",
"debug",
"(",
"'signature: %r'",
",",
"signature",
")",
"try",
":",
"sig_bytes",
"=",
"key",
"[",
"'verifier'",
"]",
"(",
"sig",
"=",
"signature",
",",
"msg",
"=",
"blob",
")",
"log",
".",
"info",
"(",
"'signature status: OK'",
")",
"except",
"formats",
".",
"ecdsa",
".",
"BadSignatureError",
":",
"log",
".",
"exception",
"(",
"'signature status: ERROR'",
")",
"raise",
"ValueError",
"(",
"'invalid ECDSA signature'",
")",
"log",
".",
"debug",
"(",
"'signature size: %d bytes'",
",",
"len",
"(",
"sig_bytes",
")",
")",
"data",
"=",
"util",
".",
"frame",
"(",
"util",
".",
"frame",
"(",
"key",
"[",
"'type'",
"]",
")",
",",
"util",
".",
"frame",
"(",
"sig_bytes",
")",
")",
"code",
"=",
"util",
".",
"pack",
"(",
"'B'",
",",
"msg_code",
"(",
"'SSH2_AGENT_SIGN_RESPONSE'",
")",
")",
"return",
"util",
".",
"frame",
"(",
"code",
",",
"data",
")"
] |
SSH v2 public key authentication is performed.
If the required key is not supported, raise KeyError
If the signature is invalid, raise ValueError
|
[
"SSH",
"v2",
"public",
"key",
"authentication",
"is",
"performed",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/protocol.py#L120-L160
|
9,932
|
romanz/trezor-agent
|
libagent/util.py
|
recv
|
def recv(conn, size):
"""
Receive bytes from connection socket or stream.
If size is struct.calcsize()-compatible format, use it to unpack the data.
Otherwise, return the plain blob as bytes.
"""
try:
fmt = size
size = struct.calcsize(fmt)
except TypeError:
fmt = None
try:
_read = conn.recv
except AttributeError:
_read = conn.read
res = io.BytesIO()
while size > 0:
buf = _read(size)
if not buf:
raise EOFError
size = size - len(buf)
res.write(buf)
res = res.getvalue()
if fmt:
return struct.unpack(fmt, res)
else:
return res
|
python
|
def recv(conn, size):
"""
Receive bytes from connection socket or stream.
If size is struct.calcsize()-compatible format, use it to unpack the data.
Otherwise, return the plain blob as bytes.
"""
try:
fmt = size
size = struct.calcsize(fmt)
except TypeError:
fmt = None
try:
_read = conn.recv
except AttributeError:
_read = conn.read
res = io.BytesIO()
while size > 0:
buf = _read(size)
if not buf:
raise EOFError
size = size - len(buf)
res.write(buf)
res = res.getvalue()
if fmt:
return struct.unpack(fmt, res)
else:
return res
|
[
"def",
"recv",
"(",
"conn",
",",
"size",
")",
":",
"try",
":",
"fmt",
"=",
"size",
"size",
"=",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"except",
"TypeError",
":",
"fmt",
"=",
"None",
"try",
":",
"_read",
"=",
"conn",
".",
"recv",
"except",
"AttributeError",
":",
"_read",
"=",
"conn",
".",
"read",
"res",
"=",
"io",
".",
"BytesIO",
"(",
")",
"while",
"size",
">",
"0",
":",
"buf",
"=",
"_read",
"(",
"size",
")",
"if",
"not",
"buf",
":",
"raise",
"EOFError",
"size",
"=",
"size",
"-",
"len",
"(",
"buf",
")",
"res",
".",
"write",
"(",
"buf",
")",
"res",
"=",
"res",
".",
"getvalue",
"(",
")",
"if",
"fmt",
":",
"return",
"struct",
".",
"unpack",
"(",
"fmt",
",",
"res",
")",
"else",
":",
"return",
"res"
] |
Receive bytes from connection socket or stream.
If size is struct.calcsize()-compatible format, use it to unpack the data.
Otherwise, return the plain blob as bytes.
|
[
"Receive",
"bytes",
"from",
"connection",
"socket",
"or",
"stream",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/util.py#L18-L46
|
9,933
|
romanz/trezor-agent
|
libagent/util.py
|
bytes2num
|
def bytes2num(s):
"""Convert MSB-first bytes to an unsigned integer."""
res = 0
for i, c in enumerate(reversed(bytearray(s))):
res += c << (i * 8)
return res
|
python
|
def bytes2num(s):
"""Convert MSB-first bytes to an unsigned integer."""
res = 0
for i, c in enumerate(reversed(bytearray(s))):
res += c << (i * 8)
return res
|
[
"def",
"bytes2num",
"(",
"s",
")",
":",
"res",
"=",
"0",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"reversed",
"(",
"bytearray",
"(",
"s",
")",
")",
")",
":",
"res",
"+=",
"c",
"<<",
"(",
"i",
"*",
"8",
")",
"return",
"res"
] |
Convert MSB-first bytes to an unsigned integer.
|
[
"Convert",
"MSB",
"-",
"first",
"bytes",
"to",
"an",
"unsigned",
"integer",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/util.py#L55-L60
|
9,934
|
romanz/trezor-agent
|
libagent/util.py
|
num2bytes
|
def num2bytes(value, size):
"""Convert an unsigned integer to MSB-first bytes with specified size."""
res = []
for _ in range(size):
res.append(value & 0xFF)
value = value >> 8
assert value == 0
return bytes(bytearray(list(reversed(res))))
|
python
|
def num2bytes(value, size):
"""Convert an unsigned integer to MSB-first bytes with specified size."""
res = []
for _ in range(size):
res.append(value & 0xFF)
value = value >> 8
assert value == 0
return bytes(bytearray(list(reversed(res))))
|
[
"def",
"num2bytes",
"(",
"value",
",",
"size",
")",
":",
"res",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"size",
")",
":",
"res",
".",
"append",
"(",
"value",
"&",
"0xFF",
")",
"value",
"=",
"value",
">>",
"8",
"assert",
"value",
"==",
"0",
"return",
"bytes",
"(",
"bytearray",
"(",
"list",
"(",
"reversed",
"(",
"res",
")",
")",
")",
")"
] |
Convert an unsigned integer to MSB-first bytes with specified size.
|
[
"Convert",
"an",
"unsigned",
"integer",
"to",
"MSB",
"-",
"first",
"bytes",
"with",
"specified",
"size",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/util.py#L63-L70
|
9,935
|
romanz/trezor-agent
|
libagent/util.py
|
frame
|
def frame(*msgs):
"""Serialize MSB-first length-prefixed frame."""
res = io.BytesIO()
for msg in msgs:
res.write(msg)
msg = res.getvalue()
return pack('L', len(msg)) + msg
|
python
|
def frame(*msgs):
"""Serialize MSB-first length-prefixed frame."""
res = io.BytesIO()
for msg in msgs:
res.write(msg)
msg = res.getvalue()
return pack('L', len(msg)) + msg
|
[
"def",
"frame",
"(",
"*",
"msgs",
")",
":",
"res",
"=",
"io",
".",
"BytesIO",
"(",
")",
"for",
"msg",
"in",
"msgs",
":",
"res",
".",
"write",
"(",
"msg",
")",
"msg",
"=",
"res",
".",
"getvalue",
"(",
")",
"return",
"pack",
"(",
"'L'",
",",
"len",
"(",
"msg",
")",
")",
"+",
"msg"
] |
Serialize MSB-first length-prefixed frame.
|
[
"Serialize",
"MSB",
"-",
"first",
"length",
"-",
"prefixed",
"frame",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/util.py#L78-L84
|
9,936
|
romanz/trezor-agent
|
libagent/util.py
|
split_bits
|
def split_bits(value, *bits):
"""
Split integer value into list of ints, according to `bits` list.
For example, split_bits(0x1234, 4, 8, 4) == [0x1, 0x23, 0x4]
"""
result = []
for b in reversed(bits):
mask = (1 << b) - 1
result.append(value & mask)
value = value >> b
assert value == 0
result.reverse()
return result
|
python
|
def split_bits(value, *bits):
"""
Split integer value into list of ints, according to `bits` list.
For example, split_bits(0x1234, 4, 8, 4) == [0x1, 0x23, 0x4]
"""
result = []
for b in reversed(bits):
mask = (1 << b) - 1
result.append(value & mask)
value = value >> b
assert value == 0
result.reverse()
return result
|
[
"def",
"split_bits",
"(",
"value",
",",
"*",
"bits",
")",
":",
"result",
"=",
"[",
"]",
"for",
"b",
"in",
"reversed",
"(",
"bits",
")",
":",
"mask",
"=",
"(",
"1",
"<<",
"b",
")",
"-",
"1",
"result",
".",
"append",
"(",
"value",
"&",
"mask",
")",
"value",
"=",
"value",
">>",
"b",
"assert",
"value",
"==",
"0",
"result",
".",
"reverse",
"(",
")",
"return",
"result"
] |
Split integer value into list of ints, according to `bits` list.
For example, split_bits(0x1234, 4, 8, 4) == [0x1, 0x23, 0x4]
|
[
"Split",
"integer",
"value",
"into",
"list",
"of",
"ints",
"according",
"to",
"bits",
"list",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/util.py#L115-L129
|
9,937
|
romanz/trezor-agent
|
libagent/util.py
|
readfmt
|
def readfmt(stream, fmt):
"""Read and unpack an object from stream, using a struct format string."""
size = struct.calcsize(fmt)
blob = stream.read(size)
return struct.unpack(fmt, blob)
|
python
|
def readfmt(stream, fmt):
"""Read and unpack an object from stream, using a struct format string."""
size = struct.calcsize(fmt)
blob = stream.read(size)
return struct.unpack(fmt, blob)
|
[
"def",
"readfmt",
"(",
"stream",
",",
"fmt",
")",
":",
"size",
"=",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"blob",
"=",
"stream",
".",
"read",
"(",
"size",
")",
"return",
"struct",
".",
"unpack",
"(",
"fmt",
",",
"blob",
")"
] |
Read and unpack an object from stream, using a struct format string.
|
[
"Read",
"and",
"unpack",
"an",
"object",
"from",
"stream",
"using",
"a",
"struct",
"format",
"string",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/util.py#L132-L136
|
9,938
|
romanz/trezor-agent
|
libagent/util.py
|
setup_logging
|
def setup_logging(verbosity, filename=None):
"""Configure logging for this tool."""
levels = [logging.WARNING, logging.INFO, logging.DEBUG]
level = levels[min(verbosity, len(levels) - 1)]
logging.root.setLevel(level)
fmt = logging.Formatter('%(asctime)s %(levelname)-12s %(message)-100s '
'[%(filename)s:%(lineno)d]')
hdlr = logging.StreamHandler() # stderr
hdlr.setFormatter(fmt)
logging.root.addHandler(hdlr)
if filename:
hdlr = logging.FileHandler(filename, 'a')
hdlr.setFormatter(fmt)
logging.root.addHandler(hdlr)
|
python
|
def setup_logging(verbosity, filename=None):
"""Configure logging for this tool."""
levels = [logging.WARNING, logging.INFO, logging.DEBUG]
level = levels[min(verbosity, len(levels) - 1)]
logging.root.setLevel(level)
fmt = logging.Formatter('%(asctime)s %(levelname)-12s %(message)-100s '
'[%(filename)s:%(lineno)d]')
hdlr = logging.StreamHandler() # stderr
hdlr.setFormatter(fmt)
logging.root.addHandler(hdlr)
if filename:
hdlr = logging.FileHandler(filename, 'a')
hdlr.setFormatter(fmt)
logging.root.addHandler(hdlr)
|
[
"def",
"setup_logging",
"(",
"verbosity",
",",
"filename",
"=",
"None",
")",
":",
"levels",
"=",
"[",
"logging",
".",
"WARNING",
",",
"logging",
".",
"INFO",
",",
"logging",
".",
"DEBUG",
"]",
"level",
"=",
"levels",
"[",
"min",
"(",
"verbosity",
",",
"len",
"(",
"levels",
")",
"-",
"1",
")",
"]",
"logging",
".",
"root",
".",
"setLevel",
"(",
"level",
")",
"fmt",
"=",
"logging",
".",
"Formatter",
"(",
"'%(asctime)s %(levelname)-12s %(message)-100s '",
"'[%(filename)s:%(lineno)d]'",
")",
"hdlr",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"# stderr",
"hdlr",
".",
"setFormatter",
"(",
"fmt",
")",
"logging",
".",
"root",
".",
"addHandler",
"(",
"hdlr",
")",
"if",
"filename",
":",
"hdlr",
"=",
"logging",
".",
"FileHandler",
"(",
"filename",
",",
"'a'",
")",
"hdlr",
".",
"setFormatter",
"(",
"fmt",
")",
"logging",
".",
"root",
".",
"addHandler",
"(",
"hdlr",
")"
] |
Configure logging for this tool.
|
[
"Configure",
"logging",
"for",
"this",
"tool",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/util.py#L183-L198
|
9,939
|
romanz/trezor-agent
|
libagent/util.py
|
which
|
def which(cmd):
"""Return full path to specified command, or raise OSError if missing."""
try:
# For Python 3
from shutil import which as _which
except ImportError:
# For Python 2
from backports.shutil_which import which as _which # pylint: disable=relative-import
full_path = _which(cmd)
if full_path is None:
raise OSError('Cannot find {!r} in $PATH'.format(cmd))
log.debug('which %r => %r', cmd, full_path)
return full_path
|
python
|
def which(cmd):
"""Return full path to specified command, or raise OSError if missing."""
try:
# For Python 3
from shutil import which as _which
except ImportError:
# For Python 2
from backports.shutil_which import which as _which # pylint: disable=relative-import
full_path = _which(cmd)
if full_path is None:
raise OSError('Cannot find {!r} in $PATH'.format(cmd))
log.debug('which %r => %r', cmd, full_path)
return full_path
|
[
"def",
"which",
"(",
"cmd",
")",
":",
"try",
":",
"# For Python 3",
"from",
"shutil",
"import",
"which",
"as",
"_which",
"except",
"ImportError",
":",
"# For Python 2",
"from",
"backports",
".",
"shutil_which",
"import",
"which",
"as",
"_which",
"# pylint: disable=relative-import",
"full_path",
"=",
"_which",
"(",
"cmd",
")",
"if",
"full_path",
"is",
"None",
":",
"raise",
"OSError",
"(",
"'Cannot find {!r} in $PATH'",
".",
"format",
"(",
"cmd",
")",
")",
"log",
".",
"debug",
"(",
"'which %r => %r'",
",",
"cmd",
",",
"full_path",
")",
"return",
"full_path"
] |
Return full path to specified command, or raise OSError if missing.
|
[
"Return",
"full",
"path",
"to",
"specified",
"command",
"or",
"raise",
"OSError",
"if",
"missing",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/util.py#L238-L250
|
9,940
|
romanz/trezor-agent
|
libagent/util.py
|
Reader.readfmt
|
def readfmt(self, fmt):
"""Read a specified object, using a struct format string."""
size = struct.calcsize(fmt)
blob = self.read(size)
obj, = struct.unpack(fmt, blob)
return obj
|
python
|
def readfmt(self, fmt):
"""Read a specified object, using a struct format string."""
size = struct.calcsize(fmt)
blob = self.read(size)
obj, = struct.unpack(fmt, blob)
return obj
|
[
"def",
"readfmt",
"(",
"self",
",",
"fmt",
")",
":",
"size",
"=",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"blob",
"=",
"self",
".",
"read",
"(",
"size",
")",
"obj",
",",
"=",
"struct",
".",
"unpack",
"(",
"fmt",
",",
"blob",
")",
"return",
"obj"
] |
Read a specified object, using a struct format string.
|
[
"Read",
"a",
"specified",
"object",
"using",
"a",
"struct",
"format",
"string",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/util.py#L157-L162
|
9,941
|
romanz/trezor-agent
|
libagent/util.py
|
Reader.read
|
def read(self, size=None):
"""Read `size` bytes from stream."""
blob = self.s.read(size)
if size is not None and len(blob) < size:
raise EOFError
if self._captured:
self._captured.write(blob)
return blob
|
python
|
def read(self, size=None):
"""Read `size` bytes from stream."""
blob = self.s.read(size)
if size is not None and len(blob) < size:
raise EOFError
if self._captured:
self._captured.write(blob)
return blob
|
[
"def",
"read",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"blob",
"=",
"self",
".",
"s",
".",
"read",
"(",
"size",
")",
"if",
"size",
"is",
"not",
"None",
"and",
"len",
"(",
"blob",
")",
"<",
"size",
":",
"raise",
"EOFError",
"if",
"self",
".",
"_captured",
":",
"self",
".",
"_captured",
".",
"write",
"(",
"blob",
")",
"return",
"blob"
] |
Read `size` bytes from stream.
|
[
"Read",
"size",
"bytes",
"from",
"stream",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/util.py#L164-L171
|
9,942
|
romanz/trezor-agent
|
libagent/util.py
|
ExpiringCache.get
|
def get(self):
"""Returns existing value, or None if deadline has expired."""
if self.timer() > self.deadline:
self.value = None
return self.value
|
python
|
def get(self):
"""Returns existing value, or None if deadline has expired."""
if self.timer() > self.deadline:
self.value = None
return self.value
|
[
"def",
"get",
"(",
"self",
")",
":",
"if",
"self",
".",
"timer",
"(",
")",
">",
"self",
".",
"deadline",
":",
"self",
".",
"value",
"=",
"None",
"return",
"self",
".",
"value"
] |
Returns existing value, or None if deadline has expired.
|
[
"Returns",
"existing",
"value",
"or",
"None",
"if",
"deadline",
"has",
"expired",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/util.py#L271-L275
|
9,943
|
romanz/trezor-agent
|
libagent/util.py
|
ExpiringCache.set
|
def set(self, value):
"""Set new value and reset the deadline for expiration."""
self.deadline = self.timer() + self.duration
self.value = value
|
python
|
def set(self, value):
"""Set new value and reset the deadline for expiration."""
self.deadline = self.timer() + self.duration
self.value = value
|
[
"def",
"set",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"deadline",
"=",
"self",
".",
"timer",
"(",
")",
"+",
"self",
".",
"duration",
"self",
".",
"value",
"=",
"value"
] |
Set new value and reset the deadline for expiration.
|
[
"Set",
"new",
"value",
"and",
"reset",
"the",
"deadline",
"for",
"expiration",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/util.py#L277-L280
|
9,944
|
romanz/trezor-agent
|
libagent/gpg/agent.py
|
sig_encode
|
def sig_encode(r, s):
"""Serialize ECDSA signature data into GPG S-expression."""
r = util.assuan_serialize(util.num2bytes(r, 32))
s = util.assuan_serialize(util.num2bytes(s, 32))
return b'(7:sig-val(5:ecdsa(1:r32:' + r + b')(1:s32:' + s + b')))'
|
python
|
def sig_encode(r, s):
"""Serialize ECDSA signature data into GPG S-expression."""
r = util.assuan_serialize(util.num2bytes(r, 32))
s = util.assuan_serialize(util.num2bytes(s, 32))
return b'(7:sig-val(5:ecdsa(1:r32:' + r + b')(1:s32:' + s + b')))'
|
[
"def",
"sig_encode",
"(",
"r",
",",
"s",
")",
":",
"r",
"=",
"util",
".",
"assuan_serialize",
"(",
"util",
".",
"num2bytes",
"(",
"r",
",",
"32",
")",
")",
"s",
"=",
"util",
".",
"assuan_serialize",
"(",
"util",
".",
"num2bytes",
"(",
"s",
",",
"32",
")",
")",
"return",
"b'(7:sig-val(5:ecdsa(1:r32:'",
"+",
"r",
"+",
"b')(1:s32:'",
"+",
"s",
"+",
"b')))'"
] |
Serialize ECDSA signature data into GPG S-expression.
|
[
"Serialize",
"ECDSA",
"signature",
"data",
"into",
"GPG",
"S",
"-",
"expression",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L24-L28
|
9,945
|
romanz/trezor-agent
|
libagent/gpg/agent.py
|
parse_ecdh
|
def parse_ecdh(line):
"""Parse ECDH request and return remote public key."""
prefix, line = line.split(b' ', 1)
assert prefix == b'D'
exp, leftover = keyring.parse(keyring.unescape(line))
log.debug('ECDH s-exp: %r', exp)
assert not leftover
label, exp = exp
assert label == b'enc-val'
assert exp[0] == b'ecdh'
items = exp[1:]
log.debug('ECDH parameters: %r', items)
return dict(items)[b'e']
|
python
|
def parse_ecdh(line):
"""Parse ECDH request and return remote public key."""
prefix, line = line.split(b' ', 1)
assert prefix == b'D'
exp, leftover = keyring.parse(keyring.unescape(line))
log.debug('ECDH s-exp: %r', exp)
assert not leftover
label, exp = exp
assert label == b'enc-val'
assert exp[0] == b'ecdh'
items = exp[1:]
log.debug('ECDH parameters: %r', items)
return dict(items)[b'e']
|
[
"def",
"parse_ecdh",
"(",
"line",
")",
":",
"prefix",
",",
"line",
"=",
"line",
".",
"split",
"(",
"b' '",
",",
"1",
")",
"assert",
"prefix",
"==",
"b'D'",
"exp",
",",
"leftover",
"=",
"keyring",
".",
"parse",
"(",
"keyring",
".",
"unescape",
"(",
"line",
")",
")",
"log",
".",
"debug",
"(",
"'ECDH s-exp: %r'",
",",
"exp",
")",
"assert",
"not",
"leftover",
"label",
",",
"exp",
"=",
"exp",
"assert",
"label",
"==",
"b'enc-val'",
"assert",
"exp",
"[",
"0",
"]",
"==",
"b'ecdh'",
"items",
"=",
"exp",
"[",
"1",
":",
"]",
"log",
".",
"debug",
"(",
"'ECDH parameters: %r'",
",",
"items",
")",
"return",
"dict",
"(",
"items",
")",
"[",
"b'e'",
"]"
] |
Parse ECDH request and return remote public key.
|
[
"Parse",
"ECDH",
"request",
"and",
"return",
"remote",
"public",
"key",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L37-L49
|
9,946
|
romanz/trezor-agent
|
libagent/gpg/agent.py
|
Handler.handle_getinfo
|
def handle_getinfo(self, conn, args):
"""Handle some of the GETINFO messages."""
result = None
if args[0] == b'version':
result = self.version
elif args[0] == b's2k_count':
# Use highest number of S2K iterations.
# https://www.gnupg.org/documentation/manuals/gnupg/OpenPGP-Options.html
# https://tools.ietf.org/html/rfc4880#section-3.7.1.3
result = '{}'.format(64 << 20).encode('ascii')
else:
log.warning('Unknown GETINFO command: %s', args)
if result:
keyring.sendline(conn, b'D ' + result)
|
python
|
def handle_getinfo(self, conn, args):
"""Handle some of the GETINFO messages."""
result = None
if args[0] == b'version':
result = self.version
elif args[0] == b's2k_count':
# Use highest number of S2K iterations.
# https://www.gnupg.org/documentation/manuals/gnupg/OpenPGP-Options.html
# https://tools.ietf.org/html/rfc4880#section-3.7.1.3
result = '{}'.format(64 << 20).encode('ascii')
else:
log.warning('Unknown GETINFO command: %s', args)
if result:
keyring.sendline(conn, b'D ' + result)
|
[
"def",
"handle_getinfo",
"(",
"self",
",",
"conn",
",",
"args",
")",
":",
"result",
"=",
"None",
"if",
"args",
"[",
"0",
"]",
"==",
"b'version'",
":",
"result",
"=",
"self",
".",
"version",
"elif",
"args",
"[",
"0",
"]",
"==",
"b's2k_count'",
":",
"# Use highest number of S2K iterations.",
"# https://www.gnupg.org/documentation/manuals/gnupg/OpenPGP-Options.html",
"# https://tools.ietf.org/html/rfc4880#section-3.7.1.3",
"result",
"=",
"'{}'",
".",
"format",
"(",
"64",
"<<",
"20",
")",
".",
"encode",
"(",
"'ascii'",
")",
"else",
":",
"log",
".",
"warning",
"(",
"'Unknown GETINFO command: %s'",
",",
"args",
")",
"if",
"result",
":",
"keyring",
".",
"sendline",
"(",
"conn",
",",
"b'D '",
"+",
"result",
")"
] |
Handle some of the GETINFO messages.
|
[
"Handle",
"some",
"of",
"the",
"GETINFO",
"messages",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L129-L143
|
9,947
|
romanz/trezor-agent
|
libagent/gpg/agent.py
|
Handler.handle_scd
|
def handle_scd(self, conn, args):
"""No support for smart-card device protocol."""
reply = {
(b'GETINFO', b'version'): self.version,
}.get(args)
if reply is None:
raise AgentError(b'ERR 100696144 No such device <SCD>')
keyring.sendline(conn, b'D ' + reply)
|
python
|
def handle_scd(self, conn, args):
"""No support for smart-card device protocol."""
reply = {
(b'GETINFO', b'version'): self.version,
}.get(args)
if reply is None:
raise AgentError(b'ERR 100696144 No such device <SCD>')
keyring.sendline(conn, b'D ' + reply)
|
[
"def",
"handle_scd",
"(",
"self",
",",
"conn",
",",
"args",
")",
":",
"reply",
"=",
"{",
"(",
"b'GETINFO'",
",",
"b'version'",
")",
":",
"self",
".",
"version",
",",
"}",
".",
"get",
"(",
"args",
")",
"if",
"reply",
"is",
"None",
":",
"raise",
"AgentError",
"(",
"b'ERR 100696144 No such device <SCD>'",
")",
"keyring",
".",
"sendline",
"(",
"conn",
",",
"b'D '",
"+",
"reply",
")"
] |
No support for smart-card device protocol.
|
[
"No",
"support",
"for",
"smart",
"-",
"card",
"device",
"protocol",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L145-L152
|
9,948
|
romanz/trezor-agent
|
libagent/gpg/agent.py
|
Handler.get_identity
|
def get_identity(self, keygrip):
"""
Returns device.interface.Identity that matches specified keygrip.
In case of missing keygrip, KeyError will be raised.
"""
keygrip_bytes = binascii.unhexlify(keygrip)
pubkey_dict, user_ids = decode.load_by_keygrip(
pubkey_bytes=self.pubkey_bytes, keygrip=keygrip_bytes)
# We assume the first user ID is used to generate TREZOR-based GPG keys.
user_id = user_ids[0]['value'].decode('utf-8')
curve_name = protocol.get_curve_name_by_oid(pubkey_dict['curve_oid'])
ecdh = (pubkey_dict['algo'] == protocol.ECDH_ALGO_ID)
identity = client.create_identity(user_id=user_id, curve_name=curve_name)
verifying_key = self.client.pubkey(identity=identity, ecdh=ecdh)
pubkey = protocol.PublicKey(
curve_name=curve_name, created=pubkey_dict['created'],
verifying_key=verifying_key, ecdh=ecdh)
assert pubkey.key_id() == pubkey_dict['key_id']
assert pubkey.keygrip() == keygrip_bytes
return identity
|
python
|
def get_identity(self, keygrip):
"""
Returns device.interface.Identity that matches specified keygrip.
In case of missing keygrip, KeyError will be raised.
"""
keygrip_bytes = binascii.unhexlify(keygrip)
pubkey_dict, user_ids = decode.load_by_keygrip(
pubkey_bytes=self.pubkey_bytes, keygrip=keygrip_bytes)
# We assume the first user ID is used to generate TREZOR-based GPG keys.
user_id = user_ids[0]['value'].decode('utf-8')
curve_name = protocol.get_curve_name_by_oid(pubkey_dict['curve_oid'])
ecdh = (pubkey_dict['algo'] == protocol.ECDH_ALGO_ID)
identity = client.create_identity(user_id=user_id, curve_name=curve_name)
verifying_key = self.client.pubkey(identity=identity, ecdh=ecdh)
pubkey = protocol.PublicKey(
curve_name=curve_name, created=pubkey_dict['created'],
verifying_key=verifying_key, ecdh=ecdh)
assert pubkey.key_id() == pubkey_dict['key_id']
assert pubkey.keygrip() == keygrip_bytes
return identity
|
[
"def",
"get_identity",
"(",
"self",
",",
"keygrip",
")",
":",
"keygrip_bytes",
"=",
"binascii",
".",
"unhexlify",
"(",
"keygrip",
")",
"pubkey_dict",
",",
"user_ids",
"=",
"decode",
".",
"load_by_keygrip",
"(",
"pubkey_bytes",
"=",
"self",
".",
"pubkey_bytes",
",",
"keygrip",
"=",
"keygrip_bytes",
")",
"# We assume the first user ID is used to generate TREZOR-based GPG keys.",
"user_id",
"=",
"user_ids",
"[",
"0",
"]",
"[",
"'value'",
"]",
".",
"decode",
"(",
"'utf-8'",
")",
"curve_name",
"=",
"protocol",
".",
"get_curve_name_by_oid",
"(",
"pubkey_dict",
"[",
"'curve_oid'",
"]",
")",
"ecdh",
"=",
"(",
"pubkey_dict",
"[",
"'algo'",
"]",
"==",
"protocol",
".",
"ECDH_ALGO_ID",
")",
"identity",
"=",
"client",
".",
"create_identity",
"(",
"user_id",
"=",
"user_id",
",",
"curve_name",
"=",
"curve_name",
")",
"verifying_key",
"=",
"self",
".",
"client",
".",
"pubkey",
"(",
"identity",
"=",
"identity",
",",
"ecdh",
"=",
"ecdh",
")",
"pubkey",
"=",
"protocol",
".",
"PublicKey",
"(",
"curve_name",
"=",
"curve_name",
",",
"created",
"=",
"pubkey_dict",
"[",
"'created'",
"]",
",",
"verifying_key",
"=",
"verifying_key",
",",
"ecdh",
"=",
"ecdh",
")",
"assert",
"pubkey",
".",
"key_id",
"(",
")",
"==",
"pubkey_dict",
"[",
"'key_id'",
"]",
"assert",
"pubkey",
".",
"keygrip",
"(",
")",
"==",
"keygrip_bytes",
"return",
"identity"
] |
Returns device.interface.Identity that matches specified keygrip.
In case of missing keygrip, KeyError will be raised.
|
[
"Returns",
"device",
".",
"interface",
".",
"Identity",
"that",
"matches",
"specified",
"keygrip",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L155-L176
|
9,949
|
romanz/trezor-agent
|
libagent/gpg/agent.py
|
Handler.pksign
|
def pksign(self, conn):
"""Sign a message digest using a private EC key."""
log.debug('signing %r digest (algo #%s)', self.digest, self.algo)
identity = self.get_identity(keygrip=self.keygrip)
r, s = self.client.sign(identity=identity,
digest=binascii.unhexlify(self.digest))
result = sig_encode(r, s)
log.debug('result: %r', result)
keyring.sendline(conn, b'D ' + result)
|
python
|
def pksign(self, conn):
"""Sign a message digest using a private EC key."""
log.debug('signing %r digest (algo #%s)', self.digest, self.algo)
identity = self.get_identity(keygrip=self.keygrip)
r, s = self.client.sign(identity=identity,
digest=binascii.unhexlify(self.digest))
result = sig_encode(r, s)
log.debug('result: %r', result)
keyring.sendline(conn, b'D ' + result)
|
[
"def",
"pksign",
"(",
"self",
",",
"conn",
")",
":",
"log",
".",
"debug",
"(",
"'signing %r digest (algo #%s)'",
",",
"self",
".",
"digest",
",",
"self",
".",
"algo",
")",
"identity",
"=",
"self",
".",
"get_identity",
"(",
"keygrip",
"=",
"self",
".",
"keygrip",
")",
"r",
",",
"s",
"=",
"self",
".",
"client",
".",
"sign",
"(",
"identity",
"=",
"identity",
",",
"digest",
"=",
"binascii",
".",
"unhexlify",
"(",
"self",
".",
"digest",
")",
")",
"result",
"=",
"sig_encode",
"(",
"r",
",",
"s",
")",
"log",
".",
"debug",
"(",
"'result: %r'",
",",
"result",
")",
"keyring",
".",
"sendline",
"(",
"conn",
",",
"b'D '",
"+",
"result",
")"
] |
Sign a message digest using a private EC key.
|
[
"Sign",
"a",
"message",
"digest",
"using",
"a",
"private",
"EC",
"key",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L178-L186
|
9,950
|
romanz/trezor-agent
|
libagent/gpg/agent.py
|
Handler.pkdecrypt
|
def pkdecrypt(self, conn):
"""Handle decryption using ECDH."""
for msg in [b'S INQUIRE_MAXLEN 4096', b'INQUIRE CIPHERTEXT']:
keyring.sendline(conn, msg)
line = keyring.recvline(conn)
assert keyring.recvline(conn) == b'END'
remote_pubkey = parse_ecdh(line)
identity = self.get_identity(keygrip=self.keygrip)
ec_point = self.client.ecdh(identity=identity, pubkey=remote_pubkey)
keyring.sendline(conn, b'D ' + _serialize_point(ec_point))
|
python
|
def pkdecrypt(self, conn):
"""Handle decryption using ECDH."""
for msg in [b'S INQUIRE_MAXLEN 4096', b'INQUIRE CIPHERTEXT']:
keyring.sendline(conn, msg)
line = keyring.recvline(conn)
assert keyring.recvline(conn) == b'END'
remote_pubkey = parse_ecdh(line)
identity = self.get_identity(keygrip=self.keygrip)
ec_point = self.client.ecdh(identity=identity, pubkey=remote_pubkey)
keyring.sendline(conn, b'D ' + _serialize_point(ec_point))
|
[
"def",
"pkdecrypt",
"(",
"self",
",",
"conn",
")",
":",
"for",
"msg",
"in",
"[",
"b'S INQUIRE_MAXLEN 4096'",
",",
"b'INQUIRE CIPHERTEXT'",
"]",
":",
"keyring",
".",
"sendline",
"(",
"conn",
",",
"msg",
")",
"line",
"=",
"keyring",
".",
"recvline",
"(",
"conn",
")",
"assert",
"keyring",
".",
"recvline",
"(",
"conn",
")",
"==",
"b'END'",
"remote_pubkey",
"=",
"parse_ecdh",
"(",
"line",
")",
"identity",
"=",
"self",
".",
"get_identity",
"(",
"keygrip",
"=",
"self",
".",
"keygrip",
")",
"ec_point",
"=",
"self",
".",
"client",
".",
"ecdh",
"(",
"identity",
"=",
"identity",
",",
"pubkey",
"=",
"remote_pubkey",
")",
"keyring",
".",
"sendline",
"(",
"conn",
",",
"b'D '",
"+",
"_serialize_point",
"(",
"ec_point",
")",
")"
] |
Handle decryption using ECDH.
|
[
"Handle",
"decryption",
"using",
"ECDH",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L188-L199
|
9,951
|
romanz/trezor-agent
|
libagent/gpg/agent.py
|
Handler.have_key
|
def have_key(self, *keygrips):
"""Check if any keygrip corresponds to a TREZOR-based key."""
for keygrip in keygrips:
try:
self.get_identity(keygrip=keygrip)
break
except KeyError as e:
log.warning('HAVEKEY(%s) failed: %s', keygrip, e)
else:
raise AgentError(b'ERR 67108881 No secret key <GPG Agent>')
|
python
|
def have_key(self, *keygrips):
"""Check if any keygrip corresponds to a TREZOR-based key."""
for keygrip in keygrips:
try:
self.get_identity(keygrip=keygrip)
break
except KeyError as e:
log.warning('HAVEKEY(%s) failed: %s', keygrip, e)
else:
raise AgentError(b'ERR 67108881 No secret key <GPG Agent>')
|
[
"def",
"have_key",
"(",
"self",
",",
"*",
"keygrips",
")",
":",
"for",
"keygrip",
"in",
"keygrips",
":",
"try",
":",
"self",
".",
"get_identity",
"(",
"keygrip",
"=",
"keygrip",
")",
"break",
"except",
"KeyError",
"as",
"e",
":",
"log",
".",
"warning",
"(",
"'HAVEKEY(%s) failed: %s'",
",",
"keygrip",
",",
"e",
")",
"else",
":",
"raise",
"AgentError",
"(",
"b'ERR 67108881 No secret key <GPG Agent>'",
")"
] |
Check if any keygrip corresponds to a TREZOR-based key.
|
[
"Check",
"if",
"any",
"keygrip",
"corresponds",
"to",
"a",
"TREZOR",
"-",
"based",
"key",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L201-L210
|
9,952
|
romanz/trezor-agent
|
libagent/gpg/agent.py
|
Handler.set_hash
|
def set_hash(self, algo, digest):
"""Set algorithm ID and hexadecimal digest for next operation."""
self.algo = algo
self.digest = digest
|
python
|
def set_hash(self, algo, digest):
"""Set algorithm ID and hexadecimal digest for next operation."""
self.algo = algo
self.digest = digest
|
[
"def",
"set_hash",
"(",
"self",
",",
"algo",
",",
"digest",
")",
":",
"self",
".",
"algo",
"=",
"algo",
"self",
".",
"digest",
"=",
"digest"
] |
Set algorithm ID and hexadecimal digest for next operation.
|
[
"Set",
"algorithm",
"ID",
"and",
"hexadecimal",
"digest",
"for",
"next",
"operation",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L216-L219
|
9,953
|
romanz/trezor-agent
|
libagent/gpg/agent.py
|
Handler.handle
|
def handle(self, conn):
"""Handle connection from GPG binary using the ASSUAN protocol."""
keyring.sendline(conn, b'OK')
for line in keyring.iterlines(conn):
parts = line.split(b' ')
command = parts[0]
args = tuple(parts[1:])
if command == b'BYE':
return
elif command == b'KILLAGENT':
keyring.sendline(conn, b'OK')
raise AgentStop()
if command not in self.handlers:
log.error('unknown request: %r', line)
continue
handler = self.handlers[command]
if handler:
try:
handler(conn, args)
except AgentError as e:
msg, = e.args
keyring.sendline(conn, msg)
continue
keyring.sendline(conn, b'OK')
|
python
|
def handle(self, conn):
"""Handle connection from GPG binary using the ASSUAN protocol."""
keyring.sendline(conn, b'OK')
for line in keyring.iterlines(conn):
parts = line.split(b' ')
command = parts[0]
args = tuple(parts[1:])
if command == b'BYE':
return
elif command == b'KILLAGENT':
keyring.sendline(conn, b'OK')
raise AgentStop()
if command not in self.handlers:
log.error('unknown request: %r', line)
continue
handler = self.handlers[command]
if handler:
try:
handler(conn, args)
except AgentError as e:
msg, = e.args
keyring.sendline(conn, msg)
continue
keyring.sendline(conn, b'OK')
|
[
"def",
"handle",
"(",
"self",
",",
"conn",
")",
":",
"keyring",
".",
"sendline",
"(",
"conn",
",",
"b'OK'",
")",
"for",
"line",
"in",
"keyring",
".",
"iterlines",
"(",
"conn",
")",
":",
"parts",
"=",
"line",
".",
"split",
"(",
"b' '",
")",
"command",
"=",
"parts",
"[",
"0",
"]",
"args",
"=",
"tuple",
"(",
"parts",
"[",
"1",
":",
"]",
")",
"if",
"command",
"==",
"b'BYE'",
":",
"return",
"elif",
"command",
"==",
"b'KILLAGENT'",
":",
"keyring",
".",
"sendline",
"(",
"conn",
",",
"b'OK'",
")",
"raise",
"AgentStop",
"(",
")",
"if",
"command",
"not",
"in",
"self",
".",
"handlers",
":",
"log",
".",
"error",
"(",
"'unknown request: %r'",
",",
"line",
")",
"continue",
"handler",
"=",
"self",
".",
"handlers",
"[",
"command",
"]",
"if",
"handler",
":",
"try",
":",
"handler",
"(",
"conn",
",",
"args",
")",
"except",
"AgentError",
"as",
"e",
":",
"msg",
",",
"=",
"e",
".",
"args",
"keyring",
".",
"sendline",
"(",
"conn",
",",
"msg",
")",
"continue",
"keyring",
".",
"sendline",
"(",
"conn",
",",
"b'OK'",
")"
] |
Handle connection from GPG binary using the ASSUAN protocol.
|
[
"Handle",
"connection",
"from",
"GPG",
"binary",
"using",
"the",
"ASSUAN",
"protocol",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L221-L247
|
9,954
|
romanz/trezor-agent
|
libagent/device/fake_device.py
|
FakeDevice.connect
|
def connect(self):
"""Return "dummy" connection."""
log.critical('NEVER USE THIS CODE FOR REAL-LIFE USE-CASES!!!')
log.critical('ONLY FOR DEBUGGING AND TESTING!!!')
# The code below uses HARD-CODED secret key - and should be used ONLY
# for GnuPG integration tests (e.g. when no real device is available).
# pylint: disable=attribute-defined-outside-init
self.secexp = 1
self.sk = ecdsa.SigningKey.from_secret_exponent(
secexp=self.secexp, curve=ecdsa.curves.NIST256p, hashfunc=hashlib.sha256)
self.vk = self.sk.get_verifying_key()
return self
|
python
|
def connect(self):
"""Return "dummy" connection."""
log.critical('NEVER USE THIS CODE FOR REAL-LIFE USE-CASES!!!')
log.critical('ONLY FOR DEBUGGING AND TESTING!!!')
# The code below uses HARD-CODED secret key - and should be used ONLY
# for GnuPG integration tests (e.g. when no real device is available).
# pylint: disable=attribute-defined-outside-init
self.secexp = 1
self.sk = ecdsa.SigningKey.from_secret_exponent(
secexp=self.secexp, curve=ecdsa.curves.NIST256p, hashfunc=hashlib.sha256)
self.vk = self.sk.get_verifying_key()
return self
|
[
"def",
"connect",
"(",
"self",
")",
":",
"log",
".",
"critical",
"(",
"'NEVER USE THIS CODE FOR REAL-LIFE USE-CASES!!!'",
")",
"log",
".",
"critical",
"(",
"'ONLY FOR DEBUGGING AND TESTING!!!'",
")",
"# The code below uses HARD-CODED secret key - and should be used ONLY",
"# for GnuPG integration tests (e.g. when no real device is available).",
"# pylint: disable=attribute-defined-outside-init",
"self",
".",
"secexp",
"=",
"1",
"self",
".",
"sk",
"=",
"ecdsa",
".",
"SigningKey",
".",
"from_secret_exponent",
"(",
"secexp",
"=",
"self",
".",
"secexp",
",",
"curve",
"=",
"ecdsa",
".",
"curves",
".",
"NIST256p",
",",
"hashfunc",
"=",
"hashlib",
".",
"sha256",
")",
"self",
".",
"vk",
"=",
"self",
".",
"sk",
".",
"get_verifying_key",
"(",
")",
"return",
"self"
] |
Return "dummy" connection.
|
[
"Return",
"dummy",
"connection",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/fake_device.py#L29-L40
|
9,955
|
romanz/trezor-agent
|
libagent/gpg/client.py
|
create_identity
|
def create_identity(user_id, curve_name):
"""Create GPG identity for hardware device."""
result = interface.Identity(identity_str='gpg://', curve_name=curve_name)
result.identity_dict['host'] = user_id
return result
|
python
|
def create_identity(user_id, curve_name):
"""Create GPG identity for hardware device."""
result = interface.Identity(identity_str='gpg://', curve_name=curve_name)
result.identity_dict['host'] = user_id
return result
|
[
"def",
"create_identity",
"(",
"user_id",
",",
"curve_name",
")",
":",
"result",
"=",
"interface",
".",
"Identity",
"(",
"identity_str",
"=",
"'gpg://'",
",",
"curve_name",
"=",
"curve_name",
")",
"result",
".",
"identity_dict",
"[",
"'host'",
"]",
"=",
"user_id",
"return",
"result"
] |
Create GPG identity for hardware device.
|
[
"Create",
"GPG",
"identity",
"for",
"hardware",
"device",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/client.py#L11-L15
|
9,956
|
romanz/trezor-agent
|
libagent/gpg/client.py
|
Client.pubkey
|
def pubkey(self, identity, ecdh=False):
"""Return public key as VerifyingKey object."""
with self.device:
pubkey = self.device.pubkey(ecdh=ecdh, identity=identity)
return formats.decompress_pubkey(
pubkey=pubkey, curve_name=identity.curve_name)
|
python
|
def pubkey(self, identity, ecdh=False):
"""Return public key as VerifyingKey object."""
with self.device:
pubkey = self.device.pubkey(ecdh=ecdh, identity=identity)
return formats.decompress_pubkey(
pubkey=pubkey, curve_name=identity.curve_name)
|
[
"def",
"pubkey",
"(",
"self",
",",
"identity",
",",
"ecdh",
"=",
"False",
")",
":",
"with",
"self",
".",
"device",
":",
"pubkey",
"=",
"self",
".",
"device",
".",
"pubkey",
"(",
"ecdh",
"=",
"ecdh",
",",
"identity",
"=",
"identity",
")",
"return",
"formats",
".",
"decompress_pubkey",
"(",
"pubkey",
"=",
"pubkey",
",",
"curve_name",
"=",
"identity",
".",
"curve_name",
")"
] |
Return public key as VerifyingKey object.
|
[
"Return",
"public",
"key",
"as",
"VerifyingKey",
"object",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/client.py#L25-L30
|
9,957
|
romanz/trezor-agent
|
libagent/gpg/client.py
|
Client.sign
|
def sign(self, identity, digest):
"""Sign the digest and return a serialized signature."""
log.info('please confirm GPG signature on %s for "%s"...',
self.device, identity.to_string())
if identity.curve_name == formats.CURVE_NIST256:
digest = digest[:32] # sign the first 256 bits
log.debug('signing digest: %s', util.hexlify(digest))
with self.device:
sig = self.device.sign(blob=digest, identity=identity)
return (util.bytes2num(sig[:32]), util.bytes2num(sig[32:]))
|
python
|
def sign(self, identity, digest):
"""Sign the digest and return a serialized signature."""
log.info('please confirm GPG signature on %s for "%s"...',
self.device, identity.to_string())
if identity.curve_name == formats.CURVE_NIST256:
digest = digest[:32] # sign the first 256 bits
log.debug('signing digest: %s', util.hexlify(digest))
with self.device:
sig = self.device.sign(blob=digest, identity=identity)
return (util.bytes2num(sig[:32]), util.bytes2num(sig[32:]))
|
[
"def",
"sign",
"(",
"self",
",",
"identity",
",",
"digest",
")",
":",
"log",
".",
"info",
"(",
"'please confirm GPG signature on %s for \"%s\"...'",
",",
"self",
".",
"device",
",",
"identity",
".",
"to_string",
"(",
")",
")",
"if",
"identity",
".",
"curve_name",
"==",
"formats",
".",
"CURVE_NIST256",
":",
"digest",
"=",
"digest",
"[",
":",
"32",
"]",
"# sign the first 256 bits",
"log",
".",
"debug",
"(",
"'signing digest: %s'",
",",
"util",
".",
"hexlify",
"(",
"digest",
")",
")",
"with",
"self",
".",
"device",
":",
"sig",
"=",
"self",
".",
"device",
".",
"sign",
"(",
"blob",
"=",
"digest",
",",
"identity",
"=",
"identity",
")",
"return",
"(",
"util",
".",
"bytes2num",
"(",
"sig",
"[",
":",
"32",
"]",
")",
",",
"util",
".",
"bytes2num",
"(",
"sig",
"[",
"32",
":",
"]",
")",
")"
] |
Sign the digest and return a serialized signature.
|
[
"Sign",
"the",
"digest",
"and",
"return",
"a",
"serialized",
"signature",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/client.py#L32-L41
|
9,958
|
romanz/trezor-agent
|
libagent/gpg/client.py
|
Client.ecdh
|
def ecdh(self, identity, pubkey):
"""Derive shared secret using ECDH from remote public key."""
log.info('please confirm GPG decryption on %s for "%s"...',
self.device, identity.to_string())
with self.device:
return self.device.ecdh(pubkey=pubkey, identity=identity)
|
python
|
def ecdh(self, identity, pubkey):
"""Derive shared secret using ECDH from remote public key."""
log.info('please confirm GPG decryption on %s for "%s"...',
self.device, identity.to_string())
with self.device:
return self.device.ecdh(pubkey=pubkey, identity=identity)
|
[
"def",
"ecdh",
"(",
"self",
",",
"identity",
",",
"pubkey",
")",
":",
"log",
".",
"info",
"(",
"'please confirm GPG decryption on %s for \"%s\"...'",
",",
"self",
".",
"device",
",",
"identity",
".",
"to_string",
"(",
")",
")",
"with",
"self",
".",
"device",
":",
"return",
"self",
".",
"device",
".",
"ecdh",
"(",
"pubkey",
"=",
"pubkey",
",",
"identity",
"=",
"identity",
")"
] |
Derive shared secret using ECDH from remote public key.
|
[
"Derive",
"shared",
"secret",
"using",
"ECDH",
"from",
"remote",
"public",
"key",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/client.py#L43-L48
|
9,959
|
romanz/trezor-agent
|
libagent/device/trezor.py
|
Trezor.connect
|
def connect(self):
"""Enumerate and connect to the first available interface."""
transport = self._defs.find_device()
if not transport:
raise interface.NotFoundError('{} not connected'.format(self))
log.debug('using transport: %s', transport)
for _ in range(5): # Retry a few times in case of PIN failures
connection = self._defs.Client(transport=transport,
ui=self.ui,
state=self.__class__.cached_state)
self._verify_version(connection)
try:
connection.ping(msg='', pin_protection=True) # unlock PIN
return connection
except (self._defs.PinException, ValueError) as e:
log.error('Invalid PIN: %s, retrying...', e)
continue
except Exception as e:
log.exception('ping failed: %s', e)
connection.close() # so the next HID open() will succeed
raise
|
python
|
def connect(self):
"""Enumerate and connect to the first available interface."""
transport = self._defs.find_device()
if not transport:
raise interface.NotFoundError('{} not connected'.format(self))
log.debug('using transport: %s', transport)
for _ in range(5): # Retry a few times in case of PIN failures
connection = self._defs.Client(transport=transport,
ui=self.ui,
state=self.__class__.cached_state)
self._verify_version(connection)
try:
connection.ping(msg='', pin_protection=True) # unlock PIN
return connection
except (self._defs.PinException, ValueError) as e:
log.error('Invalid PIN: %s, retrying...', e)
continue
except Exception as e:
log.exception('ping failed: %s', e)
connection.close() # so the next HID open() will succeed
raise
|
[
"def",
"connect",
"(",
"self",
")",
":",
"transport",
"=",
"self",
".",
"_defs",
".",
"find_device",
"(",
")",
"if",
"not",
"transport",
":",
"raise",
"interface",
".",
"NotFoundError",
"(",
"'{} not connected'",
".",
"format",
"(",
"self",
")",
")",
"log",
".",
"debug",
"(",
"'using transport: %s'",
",",
"transport",
")",
"for",
"_",
"in",
"range",
"(",
"5",
")",
":",
"# Retry a few times in case of PIN failures",
"connection",
"=",
"self",
".",
"_defs",
".",
"Client",
"(",
"transport",
"=",
"transport",
",",
"ui",
"=",
"self",
".",
"ui",
",",
"state",
"=",
"self",
".",
"__class__",
".",
"cached_state",
")",
"self",
".",
"_verify_version",
"(",
"connection",
")",
"try",
":",
"connection",
".",
"ping",
"(",
"msg",
"=",
"''",
",",
"pin_protection",
"=",
"True",
")",
"# unlock PIN",
"return",
"connection",
"except",
"(",
"self",
".",
"_defs",
".",
"PinException",
",",
"ValueError",
")",
"as",
"e",
":",
"log",
".",
"error",
"(",
"'Invalid PIN: %s, retrying...'",
",",
"e",
")",
"continue",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"exception",
"(",
"'ping failed: %s'",
",",
"e",
")",
"connection",
".",
"close",
"(",
")",
"# so the next HID open() will succeed",
"raise"
] |
Enumerate and connect to the first available interface.
|
[
"Enumerate",
"and",
"connect",
"to",
"the",
"first",
"available",
"interface",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/trezor.py#L47-L69
|
9,960
|
romanz/trezor-agent
|
libagent/device/interface.py
|
string_to_identity
|
def string_to_identity(identity_str):
"""Parse string into Identity dictionary."""
m = _identity_regexp.match(identity_str)
result = m.groupdict()
log.debug('parsed identity: %s', result)
return {k: v for k, v in result.items() if v}
|
python
|
def string_to_identity(identity_str):
"""Parse string into Identity dictionary."""
m = _identity_regexp.match(identity_str)
result = m.groupdict()
log.debug('parsed identity: %s', result)
return {k: v for k, v in result.items() if v}
|
[
"def",
"string_to_identity",
"(",
"identity_str",
")",
":",
"m",
"=",
"_identity_regexp",
".",
"match",
"(",
"identity_str",
")",
"result",
"=",
"m",
".",
"groupdict",
"(",
")",
"log",
".",
"debug",
"(",
"'parsed identity: %s'",
",",
"result",
")",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"result",
".",
"items",
"(",
")",
"if",
"v",
"}"
] |
Parse string into Identity dictionary.
|
[
"Parse",
"string",
"into",
"Identity",
"dictionary",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/interface.py#L26-L31
|
9,961
|
romanz/trezor-agent
|
libagent/device/interface.py
|
identity_to_string
|
def identity_to_string(identity_dict):
"""Dump Identity dictionary into its string representation."""
result = []
if identity_dict.get('proto'):
result.append(identity_dict['proto'] + '://')
if identity_dict.get('user'):
result.append(identity_dict['user'] + '@')
result.append(identity_dict['host'])
if identity_dict.get('port'):
result.append(':' + identity_dict['port'])
if identity_dict.get('path'):
result.append(identity_dict['path'])
log.debug('identity parts: %s', result)
return ''.join(result)
|
python
|
def identity_to_string(identity_dict):
"""Dump Identity dictionary into its string representation."""
result = []
if identity_dict.get('proto'):
result.append(identity_dict['proto'] + '://')
if identity_dict.get('user'):
result.append(identity_dict['user'] + '@')
result.append(identity_dict['host'])
if identity_dict.get('port'):
result.append(':' + identity_dict['port'])
if identity_dict.get('path'):
result.append(identity_dict['path'])
log.debug('identity parts: %s', result)
return ''.join(result)
|
[
"def",
"identity_to_string",
"(",
"identity_dict",
")",
":",
"result",
"=",
"[",
"]",
"if",
"identity_dict",
".",
"get",
"(",
"'proto'",
")",
":",
"result",
".",
"append",
"(",
"identity_dict",
"[",
"'proto'",
"]",
"+",
"'://'",
")",
"if",
"identity_dict",
".",
"get",
"(",
"'user'",
")",
":",
"result",
".",
"append",
"(",
"identity_dict",
"[",
"'user'",
"]",
"+",
"'@'",
")",
"result",
".",
"append",
"(",
"identity_dict",
"[",
"'host'",
"]",
")",
"if",
"identity_dict",
".",
"get",
"(",
"'port'",
")",
":",
"result",
".",
"append",
"(",
"':'",
"+",
"identity_dict",
"[",
"'port'",
"]",
")",
"if",
"identity_dict",
".",
"get",
"(",
"'path'",
")",
":",
"result",
".",
"append",
"(",
"identity_dict",
"[",
"'path'",
"]",
")",
"log",
".",
"debug",
"(",
"'identity parts: %s'",
",",
"result",
")",
"return",
"''",
".",
"join",
"(",
"result",
")"
] |
Dump Identity dictionary into its string representation.
|
[
"Dump",
"Identity",
"dictionary",
"into",
"its",
"string",
"representation",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/interface.py#L34-L47
|
9,962
|
romanz/trezor-agent
|
libagent/device/interface.py
|
Identity.items
|
def items(self):
"""Return a copy of identity_dict items."""
return [(k, unidecode.unidecode(v))
for k, v in self.identity_dict.items()]
|
python
|
def items(self):
"""Return a copy of identity_dict items."""
return [(k, unidecode.unidecode(v))
for k, v in self.identity_dict.items()]
|
[
"def",
"items",
"(",
"self",
")",
":",
"return",
"[",
"(",
"k",
",",
"unidecode",
".",
"unidecode",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"identity_dict",
".",
"items",
"(",
")",
"]"
] |
Return a copy of identity_dict items.
|
[
"Return",
"a",
"copy",
"of",
"identity_dict",
"items",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/interface.py#L70-L73
|
9,963
|
romanz/trezor-agent
|
libagent/device/interface.py
|
Identity.to_bytes
|
def to_bytes(self):
"""Transliterate Unicode into ASCII."""
s = identity_to_string(self.identity_dict)
return unidecode.unidecode(s).encode('ascii')
|
python
|
def to_bytes(self):
"""Transliterate Unicode into ASCII."""
s = identity_to_string(self.identity_dict)
return unidecode.unidecode(s).encode('ascii')
|
[
"def",
"to_bytes",
"(",
"self",
")",
":",
"s",
"=",
"identity_to_string",
"(",
"self",
".",
"identity_dict",
")",
"return",
"unidecode",
".",
"unidecode",
"(",
"s",
")",
".",
"encode",
"(",
"'ascii'",
")"
] |
Transliterate Unicode into ASCII.
|
[
"Transliterate",
"Unicode",
"into",
"ASCII",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/interface.py#L75-L78
|
9,964
|
romanz/trezor-agent
|
libagent/device/interface.py
|
Identity.get_curve_name
|
def get_curve_name(self, ecdh=False):
"""Return correct curve name for device operations."""
if ecdh:
return formats.get_ecdh_curve_name(self.curve_name)
else:
return self.curve_name
|
python
|
def get_curve_name(self, ecdh=False):
"""Return correct curve name for device operations."""
if ecdh:
return formats.get_ecdh_curve_name(self.curve_name)
else:
return self.curve_name
|
[
"def",
"get_curve_name",
"(",
"self",
",",
"ecdh",
"=",
"False",
")",
":",
"if",
"ecdh",
":",
"return",
"formats",
".",
"get_ecdh_curve_name",
"(",
"self",
".",
"curve_name",
")",
"else",
":",
"return",
"self",
".",
"curve_name"
] |
Return correct curve name for device operations.
|
[
"Return",
"correct",
"curve",
"name",
"for",
"device",
"operations",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/interface.py#L97-L102
|
9,965
|
romanz/trezor-agent
|
libagent/ssh/__init__.py
|
serve
|
def serve(handler, sock_path, timeout=UNIX_SOCKET_TIMEOUT):
"""
Start the ssh-agent server on a UNIX-domain socket.
If no connection is made during the specified timeout,
retry until the context is over.
"""
ssh_version = subprocess.check_output(['ssh', '-V'],
stderr=subprocess.STDOUT)
log.debug('local SSH version: %r', ssh_version)
environ = {'SSH_AUTH_SOCK': sock_path, 'SSH_AGENT_PID': str(os.getpid())}
device_mutex = threading.Lock()
with server.unix_domain_socket_server(sock_path) as sock:
sock.settimeout(timeout)
quit_event = threading.Event()
handle_conn = functools.partial(server.handle_connection,
handler=handler,
mutex=device_mutex)
kwargs = dict(sock=sock,
handle_conn=handle_conn,
quit_event=quit_event)
with server.spawn(server.server_thread, kwargs):
try:
yield environ
finally:
log.debug('closing server')
quit_event.set()
|
python
|
def serve(handler, sock_path, timeout=UNIX_SOCKET_TIMEOUT):
"""
Start the ssh-agent server on a UNIX-domain socket.
If no connection is made during the specified timeout,
retry until the context is over.
"""
ssh_version = subprocess.check_output(['ssh', '-V'],
stderr=subprocess.STDOUT)
log.debug('local SSH version: %r', ssh_version)
environ = {'SSH_AUTH_SOCK': sock_path, 'SSH_AGENT_PID': str(os.getpid())}
device_mutex = threading.Lock()
with server.unix_domain_socket_server(sock_path) as sock:
sock.settimeout(timeout)
quit_event = threading.Event()
handle_conn = functools.partial(server.handle_connection,
handler=handler,
mutex=device_mutex)
kwargs = dict(sock=sock,
handle_conn=handle_conn,
quit_event=quit_event)
with server.spawn(server.server_thread, kwargs):
try:
yield environ
finally:
log.debug('closing server')
quit_event.set()
|
[
"def",
"serve",
"(",
"handler",
",",
"sock_path",
",",
"timeout",
"=",
"UNIX_SOCKET_TIMEOUT",
")",
":",
"ssh_version",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'ssh'",
",",
"'-V'",
"]",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"log",
".",
"debug",
"(",
"'local SSH version: %r'",
",",
"ssh_version",
")",
"environ",
"=",
"{",
"'SSH_AUTH_SOCK'",
":",
"sock_path",
",",
"'SSH_AGENT_PID'",
":",
"str",
"(",
"os",
".",
"getpid",
"(",
")",
")",
"}",
"device_mutex",
"=",
"threading",
".",
"Lock",
"(",
")",
"with",
"server",
".",
"unix_domain_socket_server",
"(",
"sock_path",
")",
"as",
"sock",
":",
"sock",
".",
"settimeout",
"(",
"timeout",
")",
"quit_event",
"=",
"threading",
".",
"Event",
"(",
")",
"handle_conn",
"=",
"functools",
".",
"partial",
"(",
"server",
".",
"handle_connection",
",",
"handler",
"=",
"handler",
",",
"mutex",
"=",
"device_mutex",
")",
"kwargs",
"=",
"dict",
"(",
"sock",
"=",
"sock",
",",
"handle_conn",
"=",
"handle_conn",
",",
"quit_event",
"=",
"quit_event",
")",
"with",
"server",
".",
"spawn",
"(",
"server",
".",
"server_thread",
",",
"kwargs",
")",
":",
"try",
":",
"yield",
"environ",
"finally",
":",
"log",
".",
"debug",
"(",
"'closing server'",
")",
"quit_event",
".",
"set",
"(",
")"
] |
Start the ssh-agent server on a UNIX-domain socket.
If no connection is made during the specified timeout,
retry until the context is over.
|
[
"Start",
"the",
"ssh",
"-",
"agent",
"server",
"on",
"a",
"UNIX",
"-",
"domain",
"socket",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L124-L150
|
9,966
|
romanz/trezor-agent
|
libagent/ssh/__init__.py
|
run_server
|
def run_server(conn, command, sock_path, debug, timeout):
"""Common code for run_agent and run_git below."""
ret = 0
try:
handler = protocol.Handler(conn=conn, debug=debug)
with serve(handler=handler, sock_path=sock_path,
timeout=timeout) as env:
if command:
ret = server.run_process(command=command, environ=env)
else:
signal.pause() # wait for signal (e.g. SIGINT)
except KeyboardInterrupt:
log.info('server stopped')
return ret
|
python
|
def run_server(conn, command, sock_path, debug, timeout):
"""Common code for run_agent and run_git below."""
ret = 0
try:
handler = protocol.Handler(conn=conn, debug=debug)
with serve(handler=handler, sock_path=sock_path,
timeout=timeout) as env:
if command:
ret = server.run_process(command=command, environ=env)
else:
signal.pause() # wait for signal (e.g. SIGINT)
except KeyboardInterrupt:
log.info('server stopped')
return ret
|
[
"def",
"run_server",
"(",
"conn",
",",
"command",
",",
"sock_path",
",",
"debug",
",",
"timeout",
")",
":",
"ret",
"=",
"0",
"try",
":",
"handler",
"=",
"protocol",
".",
"Handler",
"(",
"conn",
"=",
"conn",
",",
"debug",
"=",
"debug",
")",
"with",
"serve",
"(",
"handler",
"=",
"handler",
",",
"sock_path",
"=",
"sock_path",
",",
"timeout",
"=",
"timeout",
")",
"as",
"env",
":",
"if",
"command",
":",
"ret",
"=",
"server",
".",
"run_process",
"(",
"command",
"=",
"command",
",",
"environ",
"=",
"env",
")",
"else",
":",
"signal",
".",
"pause",
"(",
")",
"# wait for signal (e.g. SIGINT)",
"except",
"KeyboardInterrupt",
":",
"log",
".",
"info",
"(",
"'server stopped'",
")",
"return",
"ret"
] |
Common code for run_agent and run_git below.
|
[
"Common",
"code",
"for",
"run_agent",
"and",
"run_git",
"below",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L153-L166
|
9,967
|
romanz/trezor-agent
|
libagent/ssh/__init__.py
|
handle_connection_error
|
def handle_connection_error(func):
"""Fail with non-zero exit code."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except device.interface.NotFoundError as e:
log.error('Connection error (try unplugging and replugging your device): %s', e)
return 1
return wrapper
|
python
|
def handle_connection_error(func):
"""Fail with non-zero exit code."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except device.interface.NotFoundError as e:
log.error('Connection error (try unplugging and replugging your device): %s', e)
return 1
return wrapper
|
[
"def",
"handle_connection_error",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"device",
".",
"interface",
".",
"NotFoundError",
"as",
"e",
":",
"log",
".",
"error",
"(",
"'Connection error (try unplugging and replugging your device): %s'",
",",
"e",
")",
"return",
"1",
"return",
"wrapper"
] |
Fail with non-zero exit code.
|
[
"Fail",
"with",
"non",
"-",
"zero",
"exit",
"code",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L169-L178
|
9,968
|
romanz/trezor-agent
|
libagent/ssh/__init__.py
|
parse_config
|
def parse_config(contents):
"""Parse config file into a list of Identity objects."""
for identity_str, curve_name in re.findall(r'\<(.*?)\|(.*?)\>', contents):
yield device.interface.Identity(identity_str=identity_str,
curve_name=curve_name)
|
python
|
def parse_config(contents):
"""Parse config file into a list of Identity objects."""
for identity_str, curve_name in re.findall(r'\<(.*?)\|(.*?)\>', contents):
yield device.interface.Identity(identity_str=identity_str,
curve_name=curve_name)
|
[
"def",
"parse_config",
"(",
"contents",
")",
":",
"for",
"identity_str",
",",
"curve_name",
"in",
"re",
".",
"findall",
"(",
"r'\\<(.*?)\\|(.*?)\\>'",
",",
"contents",
")",
":",
"yield",
"device",
".",
"interface",
".",
"Identity",
"(",
"identity_str",
"=",
"identity_str",
",",
"curve_name",
"=",
"curve_name",
")"
] |
Parse config file into a list of Identity objects.
|
[
"Parse",
"config",
"file",
"into",
"a",
"list",
"of",
"Identity",
"objects",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L181-L185
|
9,969
|
romanz/trezor-agent
|
libagent/ssh/__init__.py
|
main
|
def main(device_type):
"""Run ssh-agent using given hardware client factory."""
args = create_agent_parser(device_type=device_type).parse_args()
util.setup_logging(verbosity=args.verbose, filename=args.log_file)
public_keys = None
filename = None
if args.identity.startswith('/'):
filename = args.identity
contents = open(filename, 'rb').read().decode('utf-8')
# Allow loading previously exported SSH public keys
if filename.endswith('.pub'):
public_keys = list(import_public_keys(contents))
identities = list(parse_config(contents))
else:
identities = [device.interface.Identity(
identity_str=args.identity, curve_name=args.ecdsa_curve_name)]
for index, identity in enumerate(identities):
identity.identity_dict['proto'] = u'ssh'
log.info('identity #%d: %s', index, identity.to_string())
# override default PIN/passphrase entry tools (relevant for TREZOR/Keepkey):
device_type.ui = device.ui.UI(device_type=device_type, config=vars(args))
device_type.ui.cached_passphrase_ack = util.ExpiringCache(
args.cache_expiry_seconds)
conn = JustInTimeConnection(
conn_factory=lambda: client.Client(device_type()),
identities=identities, public_keys=public_keys)
sock_path = _get_sock_path(args)
command = args.command
context = _dummy_context()
if args.connect:
command = ['ssh'] + ssh_args(conn) + args.command
elif args.mosh:
command = ['mosh'] + mosh_args(conn) + args.command
elif args.daemonize:
out = 'SSH_AUTH_SOCK={0}; export SSH_AUTH_SOCK;\n'.format(sock_path)
sys.stdout.write(out)
sys.stdout.flush()
context = daemon.DaemonContext()
log.info('running the agent as a daemon on %s', sock_path)
elif args.foreground:
log.info('running the agent on %s', sock_path)
use_shell = bool(args.shell)
if use_shell:
command = os.environ['SHELL']
sys.stdin.close()
if command or args.daemonize or args.foreground:
with context:
return run_server(conn=conn, command=command, sock_path=sock_path,
debug=args.debug, timeout=args.timeout)
else:
for pk in conn.public_keys():
sys.stdout.write(pk)
return 0
|
python
|
def main(device_type):
"""Run ssh-agent using given hardware client factory."""
args = create_agent_parser(device_type=device_type).parse_args()
util.setup_logging(verbosity=args.verbose, filename=args.log_file)
public_keys = None
filename = None
if args.identity.startswith('/'):
filename = args.identity
contents = open(filename, 'rb').read().decode('utf-8')
# Allow loading previously exported SSH public keys
if filename.endswith('.pub'):
public_keys = list(import_public_keys(contents))
identities = list(parse_config(contents))
else:
identities = [device.interface.Identity(
identity_str=args.identity, curve_name=args.ecdsa_curve_name)]
for index, identity in enumerate(identities):
identity.identity_dict['proto'] = u'ssh'
log.info('identity #%d: %s', index, identity.to_string())
# override default PIN/passphrase entry tools (relevant for TREZOR/Keepkey):
device_type.ui = device.ui.UI(device_type=device_type, config=vars(args))
device_type.ui.cached_passphrase_ack = util.ExpiringCache(
args.cache_expiry_seconds)
conn = JustInTimeConnection(
conn_factory=lambda: client.Client(device_type()),
identities=identities, public_keys=public_keys)
sock_path = _get_sock_path(args)
command = args.command
context = _dummy_context()
if args.connect:
command = ['ssh'] + ssh_args(conn) + args.command
elif args.mosh:
command = ['mosh'] + mosh_args(conn) + args.command
elif args.daemonize:
out = 'SSH_AUTH_SOCK={0}; export SSH_AUTH_SOCK;\n'.format(sock_path)
sys.stdout.write(out)
sys.stdout.flush()
context = daemon.DaemonContext()
log.info('running the agent as a daemon on %s', sock_path)
elif args.foreground:
log.info('running the agent on %s', sock_path)
use_shell = bool(args.shell)
if use_shell:
command = os.environ['SHELL']
sys.stdin.close()
if command or args.daemonize or args.foreground:
with context:
return run_server(conn=conn, command=command, sock_path=sock_path,
debug=args.debug, timeout=args.timeout)
else:
for pk in conn.public_keys():
sys.stdout.write(pk)
return 0
|
[
"def",
"main",
"(",
"device_type",
")",
":",
"args",
"=",
"create_agent_parser",
"(",
"device_type",
"=",
"device_type",
")",
".",
"parse_args",
"(",
")",
"util",
".",
"setup_logging",
"(",
"verbosity",
"=",
"args",
".",
"verbose",
",",
"filename",
"=",
"args",
".",
"log_file",
")",
"public_keys",
"=",
"None",
"filename",
"=",
"None",
"if",
"args",
".",
"identity",
".",
"startswith",
"(",
"'/'",
")",
":",
"filename",
"=",
"args",
".",
"identity",
"contents",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"# Allow loading previously exported SSH public keys",
"if",
"filename",
".",
"endswith",
"(",
"'.pub'",
")",
":",
"public_keys",
"=",
"list",
"(",
"import_public_keys",
"(",
"contents",
")",
")",
"identities",
"=",
"list",
"(",
"parse_config",
"(",
"contents",
")",
")",
"else",
":",
"identities",
"=",
"[",
"device",
".",
"interface",
".",
"Identity",
"(",
"identity_str",
"=",
"args",
".",
"identity",
",",
"curve_name",
"=",
"args",
".",
"ecdsa_curve_name",
")",
"]",
"for",
"index",
",",
"identity",
"in",
"enumerate",
"(",
"identities",
")",
":",
"identity",
".",
"identity_dict",
"[",
"'proto'",
"]",
"=",
"u'ssh'",
"log",
".",
"info",
"(",
"'identity #%d: %s'",
",",
"index",
",",
"identity",
".",
"to_string",
"(",
")",
")",
"# override default PIN/passphrase entry tools (relevant for TREZOR/Keepkey):",
"device_type",
".",
"ui",
"=",
"device",
".",
"ui",
".",
"UI",
"(",
"device_type",
"=",
"device_type",
",",
"config",
"=",
"vars",
"(",
"args",
")",
")",
"device_type",
".",
"ui",
".",
"cached_passphrase_ack",
"=",
"util",
".",
"ExpiringCache",
"(",
"args",
".",
"cache_expiry_seconds",
")",
"conn",
"=",
"JustInTimeConnection",
"(",
"conn_factory",
"=",
"lambda",
":",
"client",
".",
"Client",
"(",
"device_type",
"(",
")",
")",
",",
"identities",
"=",
"identities",
",",
"public_keys",
"=",
"public_keys",
")",
"sock_path",
"=",
"_get_sock_path",
"(",
"args",
")",
"command",
"=",
"args",
".",
"command",
"context",
"=",
"_dummy_context",
"(",
")",
"if",
"args",
".",
"connect",
":",
"command",
"=",
"[",
"'ssh'",
"]",
"+",
"ssh_args",
"(",
"conn",
")",
"+",
"args",
".",
"command",
"elif",
"args",
".",
"mosh",
":",
"command",
"=",
"[",
"'mosh'",
"]",
"+",
"mosh_args",
"(",
"conn",
")",
"+",
"args",
".",
"command",
"elif",
"args",
".",
"daemonize",
":",
"out",
"=",
"'SSH_AUTH_SOCK={0}; export SSH_AUTH_SOCK;\\n'",
".",
"format",
"(",
"sock_path",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"out",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"context",
"=",
"daemon",
".",
"DaemonContext",
"(",
")",
"log",
".",
"info",
"(",
"'running the agent as a daemon on %s'",
",",
"sock_path",
")",
"elif",
"args",
".",
"foreground",
":",
"log",
".",
"info",
"(",
"'running the agent on %s'",
",",
"sock_path",
")",
"use_shell",
"=",
"bool",
"(",
"args",
".",
"shell",
")",
"if",
"use_shell",
":",
"command",
"=",
"os",
".",
"environ",
"[",
"'SHELL'",
"]",
"sys",
".",
"stdin",
".",
"close",
"(",
")",
"if",
"command",
"or",
"args",
".",
"daemonize",
"or",
"args",
".",
"foreground",
":",
"with",
"context",
":",
"return",
"run_server",
"(",
"conn",
"=",
"conn",
",",
"command",
"=",
"command",
",",
"sock_path",
"=",
"sock_path",
",",
"debug",
"=",
"args",
".",
"debug",
",",
"timeout",
"=",
"args",
".",
"timeout",
")",
"else",
":",
"for",
"pk",
"in",
"conn",
".",
"public_keys",
"(",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"pk",
")",
"return",
"0"
] |
Run ssh-agent using given hardware client factory.
|
[
"Run",
"ssh",
"-",
"agent",
"using",
"given",
"hardware",
"client",
"factory",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L255-L313
|
9,970
|
romanz/trezor-agent
|
libagent/ssh/__init__.py
|
JustInTimeConnection.parse_public_keys
|
def parse_public_keys(self):
"""Parse SSH public keys into dictionaries."""
public_keys = [formats.import_public_key(pk)
for pk in self.public_keys()]
for pk, identity in zip(public_keys, self.identities):
pk['identity'] = identity
return public_keys
|
python
|
def parse_public_keys(self):
"""Parse SSH public keys into dictionaries."""
public_keys = [formats.import_public_key(pk)
for pk in self.public_keys()]
for pk, identity in zip(public_keys, self.identities):
pk['identity'] = identity
return public_keys
|
[
"def",
"parse_public_keys",
"(",
"self",
")",
":",
"public_keys",
"=",
"[",
"formats",
".",
"import_public_key",
"(",
"pk",
")",
"for",
"pk",
"in",
"self",
".",
"public_keys",
"(",
")",
"]",
"for",
"pk",
",",
"identity",
"in",
"zip",
"(",
"public_keys",
",",
"self",
".",
"identities",
")",
":",
"pk",
"[",
"'identity'",
"]",
"=",
"identity",
"return",
"public_keys"
] |
Parse SSH public keys into dictionaries.
|
[
"Parse",
"SSH",
"public",
"keys",
"into",
"dictionaries",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L213-L219
|
9,971
|
romanz/trezor-agent
|
libagent/ssh/__init__.py
|
JustInTimeConnection.public_keys_as_files
|
def public_keys_as_files(self):
"""Store public keys as temporary SSH identity files."""
if not self.public_keys_tempfiles:
for pk in self.public_keys():
f = tempfile.NamedTemporaryFile(prefix='trezor-ssh-pubkey-', mode='w')
f.write(pk)
f.flush()
self.public_keys_tempfiles.append(f)
return self.public_keys_tempfiles
|
python
|
def public_keys_as_files(self):
"""Store public keys as temporary SSH identity files."""
if not self.public_keys_tempfiles:
for pk in self.public_keys():
f = tempfile.NamedTemporaryFile(prefix='trezor-ssh-pubkey-', mode='w')
f.write(pk)
f.flush()
self.public_keys_tempfiles.append(f)
return self.public_keys_tempfiles
|
[
"def",
"public_keys_as_files",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"public_keys_tempfiles",
":",
"for",
"pk",
"in",
"self",
".",
"public_keys",
"(",
")",
":",
"f",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"prefix",
"=",
"'trezor-ssh-pubkey-'",
",",
"mode",
"=",
"'w'",
")",
"f",
".",
"write",
"(",
"pk",
")",
"f",
".",
"flush",
"(",
")",
"self",
".",
"public_keys_tempfiles",
".",
"append",
"(",
"f",
")",
"return",
"self",
".",
"public_keys_tempfiles"
] |
Store public keys as temporary SSH identity files.
|
[
"Store",
"public",
"keys",
"as",
"temporary",
"SSH",
"identity",
"files",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L221-L230
|
9,972
|
romanz/trezor-agent
|
libagent/ssh/__init__.py
|
JustInTimeConnection.sign
|
def sign(self, blob, identity):
"""Sign a given blob using the specified identity on the device."""
conn = self.conn_factory()
return conn.sign_ssh_challenge(blob=blob, identity=identity)
|
python
|
def sign(self, blob, identity):
"""Sign a given blob using the specified identity on the device."""
conn = self.conn_factory()
return conn.sign_ssh_challenge(blob=blob, identity=identity)
|
[
"def",
"sign",
"(",
"self",
",",
"blob",
",",
"identity",
")",
":",
"conn",
"=",
"self",
".",
"conn_factory",
"(",
")",
"return",
"conn",
".",
"sign_ssh_challenge",
"(",
"blob",
"=",
"blob",
",",
"identity",
"=",
"identity",
")"
] |
Sign a given blob using the specified identity on the device.
|
[
"Sign",
"a",
"given",
"blob",
"using",
"the",
"specified",
"identity",
"on",
"the",
"device",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L232-L235
|
9,973
|
romanz/trezor-agent
|
libagent/gpg/protocol.py
|
packet
|
def packet(tag, blob):
"""Create small GPG packet."""
assert len(blob) < 2**32
if len(blob) < 2**8:
length_type = 0
elif len(blob) < 2**16:
length_type = 1
else:
length_type = 2
fmt = ['>B', '>H', '>L'][length_type]
leading_byte = 0x80 | (tag << 2) | (length_type)
return struct.pack('>B', leading_byte) + util.prefix_len(fmt, blob)
|
python
|
def packet(tag, blob):
"""Create small GPG packet."""
assert len(blob) < 2**32
if len(blob) < 2**8:
length_type = 0
elif len(blob) < 2**16:
length_type = 1
else:
length_type = 2
fmt = ['>B', '>H', '>L'][length_type]
leading_byte = 0x80 | (tag << 2) | (length_type)
return struct.pack('>B', leading_byte) + util.prefix_len(fmt, blob)
|
[
"def",
"packet",
"(",
"tag",
",",
"blob",
")",
":",
"assert",
"len",
"(",
"blob",
")",
"<",
"2",
"**",
"32",
"if",
"len",
"(",
"blob",
")",
"<",
"2",
"**",
"8",
":",
"length_type",
"=",
"0",
"elif",
"len",
"(",
"blob",
")",
"<",
"2",
"**",
"16",
":",
"length_type",
"=",
"1",
"else",
":",
"length_type",
"=",
"2",
"fmt",
"=",
"[",
"'>B'",
",",
"'>H'",
",",
"'>L'",
"]",
"[",
"length_type",
"]",
"leading_byte",
"=",
"0x80",
"|",
"(",
"tag",
"<<",
"2",
")",
"|",
"(",
"length_type",
")",
"return",
"struct",
".",
"pack",
"(",
"'>B'",
",",
"leading_byte",
")",
"+",
"util",
".",
"prefix_len",
"(",
"fmt",
",",
"blob",
")"
] |
Create small GPG packet.
|
[
"Create",
"small",
"GPG",
"packet",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L13-L26
|
9,974
|
romanz/trezor-agent
|
libagent/gpg/protocol.py
|
subpacket
|
def subpacket(subpacket_type, fmt, *values):
"""Create GPG subpacket."""
blob = struct.pack(fmt, *values) if values else fmt
return struct.pack('>B', subpacket_type) + blob
|
python
|
def subpacket(subpacket_type, fmt, *values):
"""Create GPG subpacket."""
blob = struct.pack(fmt, *values) if values else fmt
return struct.pack('>B', subpacket_type) + blob
|
[
"def",
"subpacket",
"(",
"subpacket_type",
",",
"fmt",
",",
"*",
"values",
")",
":",
"blob",
"=",
"struct",
".",
"pack",
"(",
"fmt",
",",
"*",
"values",
")",
"if",
"values",
"else",
"fmt",
"return",
"struct",
".",
"pack",
"(",
"'>B'",
",",
"subpacket_type",
")",
"+",
"blob"
] |
Create GPG subpacket.
|
[
"Create",
"GPG",
"subpacket",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L29-L32
|
9,975
|
romanz/trezor-agent
|
libagent/gpg/protocol.py
|
subpacket_prefix_len
|
def subpacket_prefix_len(item):
"""Prefix subpacket length according to RFC 4880 section-5.2.3.1."""
n = len(item)
if n >= 8384:
prefix = b'\xFF' + struct.pack('>L', n)
elif n >= 192:
n = n - 192
prefix = struct.pack('BB', (n // 256) + 192, n % 256)
else:
prefix = struct.pack('B', n)
return prefix + item
|
python
|
def subpacket_prefix_len(item):
"""Prefix subpacket length according to RFC 4880 section-5.2.3.1."""
n = len(item)
if n >= 8384:
prefix = b'\xFF' + struct.pack('>L', n)
elif n >= 192:
n = n - 192
prefix = struct.pack('BB', (n // 256) + 192, n % 256)
else:
prefix = struct.pack('B', n)
return prefix + item
|
[
"def",
"subpacket_prefix_len",
"(",
"item",
")",
":",
"n",
"=",
"len",
"(",
"item",
")",
"if",
"n",
">=",
"8384",
":",
"prefix",
"=",
"b'\\xFF'",
"+",
"struct",
".",
"pack",
"(",
"'>L'",
",",
"n",
")",
"elif",
"n",
">=",
"192",
":",
"n",
"=",
"n",
"-",
"192",
"prefix",
"=",
"struct",
".",
"pack",
"(",
"'BB'",
",",
"(",
"n",
"//",
"256",
")",
"+",
"192",
",",
"n",
"%",
"256",
")",
"else",
":",
"prefix",
"=",
"struct",
".",
"pack",
"(",
"'B'",
",",
"n",
")",
"return",
"prefix",
"+",
"item"
] |
Prefix subpacket length according to RFC 4880 section-5.2.3.1.
|
[
"Prefix",
"subpacket",
"length",
"according",
"to",
"RFC",
"4880",
"section",
"-",
"5",
".",
"2",
".",
"3",
".",
"1",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L55-L65
|
9,976
|
romanz/trezor-agent
|
libagent/gpg/protocol.py
|
subpackets
|
def subpackets(*items):
"""Serialize several GPG subpackets."""
prefixed = [subpacket_prefix_len(item) for item in items]
return util.prefix_len('>H', b''.join(prefixed))
|
python
|
def subpackets(*items):
"""Serialize several GPG subpackets."""
prefixed = [subpacket_prefix_len(item) for item in items]
return util.prefix_len('>H', b''.join(prefixed))
|
[
"def",
"subpackets",
"(",
"*",
"items",
")",
":",
"prefixed",
"=",
"[",
"subpacket_prefix_len",
"(",
"item",
")",
"for",
"item",
"in",
"items",
"]",
"return",
"util",
".",
"prefix_len",
"(",
"'>H'",
",",
"b''",
".",
"join",
"(",
"prefixed",
")",
")"
] |
Serialize several GPG subpackets.
|
[
"Serialize",
"several",
"GPG",
"subpackets",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L68-L71
|
9,977
|
romanz/trezor-agent
|
libagent/gpg/protocol.py
|
mpi
|
def mpi(value):
"""Serialize multipresicion integer using GPG format."""
bits = value.bit_length()
data_size = (bits + 7) // 8
data_bytes = bytearray(data_size)
for i in range(data_size):
data_bytes[i] = value & 0xFF
value = value >> 8
data_bytes.reverse()
return struct.pack('>H', bits) + bytes(data_bytes)
|
python
|
def mpi(value):
"""Serialize multipresicion integer using GPG format."""
bits = value.bit_length()
data_size = (bits + 7) // 8
data_bytes = bytearray(data_size)
for i in range(data_size):
data_bytes[i] = value & 0xFF
value = value >> 8
data_bytes.reverse()
return struct.pack('>H', bits) + bytes(data_bytes)
|
[
"def",
"mpi",
"(",
"value",
")",
":",
"bits",
"=",
"value",
".",
"bit_length",
"(",
")",
"data_size",
"=",
"(",
"bits",
"+",
"7",
")",
"//",
"8",
"data_bytes",
"=",
"bytearray",
"(",
"data_size",
")",
"for",
"i",
"in",
"range",
"(",
"data_size",
")",
":",
"data_bytes",
"[",
"i",
"]",
"=",
"value",
"&",
"0xFF",
"value",
"=",
"value",
">>",
"8",
"data_bytes",
".",
"reverse",
"(",
")",
"return",
"struct",
".",
"pack",
"(",
"'>H'",
",",
"bits",
")",
"+",
"bytes",
"(",
"data_bytes",
")"
] |
Serialize multipresicion integer using GPG format.
|
[
"Serialize",
"multipresicion",
"integer",
"using",
"GPG",
"format",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L74-L84
|
9,978
|
romanz/trezor-agent
|
libagent/gpg/protocol.py
|
keygrip_nist256
|
def keygrip_nist256(vk):
"""Compute keygrip for NIST256 curve public keys."""
curve = vk.curve.curve
gen = vk.curve.generator
g = (4 << 512) | (gen.x() << 256) | gen.y()
point = vk.pubkey.point
q = (4 << 512) | (point.x() << 256) | point.y()
return _compute_keygrip([
['p', util.num2bytes(curve.p(), size=32)],
['a', util.num2bytes(curve.a() % curve.p(), size=32)],
['b', util.num2bytes(curve.b() % curve.p(), size=32)],
['g', util.num2bytes(g, size=65)],
['n', util.num2bytes(vk.curve.order, size=32)],
['q', util.num2bytes(q, size=65)],
])
|
python
|
def keygrip_nist256(vk):
"""Compute keygrip for NIST256 curve public keys."""
curve = vk.curve.curve
gen = vk.curve.generator
g = (4 << 512) | (gen.x() << 256) | gen.y()
point = vk.pubkey.point
q = (4 << 512) | (point.x() << 256) | point.y()
return _compute_keygrip([
['p', util.num2bytes(curve.p(), size=32)],
['a', util.num2bytes(curve.a() % curve.p(), size=32)],
['b', util.num2bytes(curve.b() % curve.p(), size=32)],
['g', util.num2bytes(g, size=65)],
['n', util.num2bytes(vk.curve.order, size=32)],
['q', util.num2bytes(q, size=65)],
])
|
[
"def",
"keygrip_nist256",
"(",
"vk",
")",
":",
"curve",
"=",
"vk",
".",
"curve",
".",
"curve",
"gen",
"=",
"vk",
".",
"curve",
".",
"generator",
"g",
"=",
"(",
"4",
"<<",
"512",
")",
"|",
"(",
"gen",
".",
"x",
"(",
")",
"<<",
"256",
")",
"|",
"gen",
".",
"y",
"(",
")",
"point",
"=",
"vk",
".",
"pubkey",
".",
"point",
"q",
"=",
"(",
"4",
"<<",
"512",
")",
"|",
"(",
"point",
".",
"x",
"(",
")",
"<<",
"256",
")",
"|",
"point",
".",
"y",
"(",
")",
"return",
"_compute_keygrip",
"(",
"[",
"[",
"'p'",
",",
"util",
".",
"num2bytes",
"(",
"curve",
".",
"p",
"(",
")",
",",
"size",
"=",
"32",
")",
"]",
",",
"[",
"'a'",
",",
"util",
".",
"num2bytes",
"(",
"curve",
".",
"a",
"(",
")",
"%",
"curve",
".",
"p",
"(",
")",
",",
"size",
"=",
"32",
")",
"]",
",",
"[",
"'b'",
",",
"util",
".",
"num2bytes",
"(",
"curve",
".",
"b",
"(",
")",
"%",
"curve",
".",
"p",
"(",
")",
",",
"size",
"=",
"32",
")",
"]",
",",
"[",
"'g'",
",",
"util",
".",
"num2bytes",
"(",
"g",
",",
"size",
"=",
"65",
")",
"]",
",",
"[",
"'n'",
",",
"util",
".",
"num2bytes",
"(",
"vk",
".",
"curve",
".",
"order",
",",
"size",
"=",
"32",
")",
"]",
",",
"[",
"'q'",
",",
"util",
".",
"num2bytes",
"(",
"q",
",",
"size",
"=",
"65",
")",
"]",
",",
"]",
")"
] |
Compute keygrip for NIST256 curve public keys.
|
[
"Compute",
"keygrip",
"for",
"NIST256",
"curve",
"public",
"keys",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L107-L122
|
9,979
|
romanz/trezor-agent
|
libagent/gpg/protocol.py
|
keygrip_ed25519
|
def keygrip_ed25519(vk):
"""Compute keygrip for Ed25519 public keys."""
# pylint: disable=line-too-long
return _compute_keygrip([
['p', util.num2bytes(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED, size=32)], # nopep8
['a', b'\x01'],
['b', util.num2bytes(0x2DFC9311D490018C7338BF8688861767FF8FF5B2BEBE27548A14B235ECA6874A, size=32)], # nopep8
['g', util.num2bytes(0x04216936D3CD6E53FEC0A4E231FDD6DC5C692CC7609525A7B2C9562D608F25D51A6666666666666666666666666666666666666666666666666666666666666658, size=65)], # nopep8
['n', util.num2bytes(0x1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED, size=32)], # nopep8
['q', vk.to_bytes()],
])
|
python
|
def keygrip_ed25519(vk):
"""Compute keygrip for Ed25519 public keys."""
# pylint: disable=line-too-long
return _compute_keygrip([
['p', util.num2bytes(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED, size=32)], # nopep8
['a', b'\x01'],
['b', util.num2bytes(0x2DFC9311D490018C7338BF8688861767FF8FF5B2BEBE27548A14B235ECA6874A, size=32)], # nopep8
['g', util.num2bytes(0x04216936D3CD6E53FEC0A4E231FDD6DC5C692CC7609525A7B2C9562D608F25D51A6666666666666666666666666666666666666666666666666666666666666658, size=65)], # nopep8
['n', util.num2bytes(0x1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED, size=32)], # nopep8
['q', vk.to_bytes()],
])
|
[
"def",
"keygrip_ed25519",
"(",
"vk",
")",
":",
"# pylint: disable=line-too-long",
"return",
"_compute_keygrip",
"(",
"[",
"[",
"'p'",
",",
"util",
".",
"num2bytes",
"(",
"0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED",
",",
"size",
"=",
"32",
")",
"]",
",",
"# nopep8",
"[",
"'a'",
",",
"b'\\x01'",
"]",
",",
"[",
"'b'",
",",
"util",
".",
"num2bytes",
"(",
"0x2DFC9311D490018C7338BF8688861767FF8FF5B2BEBE27548A14B235ECA6874A",
",",
"size",
"=",
"32",
")",
"]",
",",
"# nopep8",
"[",
"'g'",
",",
"util",
".",
"num2bytes",
"(",
"0x04216936D3CD6E53FEC0A4E231FDD6DC5C692CC7609525A7B2C9562D608F25D51A6666666666666666666666666666666666666666666666666666666666666658",
",",
"size",
"=",
"65",
")",
"]",
",",
"# nopep8",
"[",
"'n'",
",",
"util",
".",
"num2bytes",
"(",
"0x1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED",
",",
"size",
"=",
"32",
")",
"]",
",",
"# nopep8",
"[",
"'q'",
",",
"vk",
".",
"to_bytes",
"(",
")",
"]",
",",
"]",
")"
] |
Compute keygrip for Ed25519 public keys.
|
[
"Compute",
"keygrip",
"for",
"Ed25519",
"public",
"keys",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L125-L135
|
9,980
|
romanz/trezor-agent
|
libagent/gpg/protocol.py
|
keygrip_curve25519
|
def keygrip_curve25519(vk):
"""Compute keygrip for Curve25519 public keys."""
# pylint: disable=line-too-long
return _compute_keygrip([
['p', util.num2bytes(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED, size=32)], # nopep8
['a', b'\x01\xDB\x41'],
['b', b'\x01'],
['g', util.num2bytes(0x04000000000000000000000000000000000000000000000000000000000000000920ae19a1b8a086b4e01edd2c7748d14c923d4d7e6d7c61b229e9c5a27eced3d9, size=65)], # nopep8
['n', util.num2bytes(0x1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED, size=32)], # nopep8
['q', vk.to_bytes()],
])
|
python
|
def keygrip_curve25519(vk):
"""Compute keygrip for Curve25519 public keys."""
# pylint: disable=line-too-long
return _compute_keygrip([
['p', util.num2bytes(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED, size=32)], # nopep8
['a', b'\x01\xDB\x41'],
['b', b'\x01'],
['g', util.num2bytes(0x04000000000000000000000000000000000000000000000000000000000000000920ae19a1b8a086b4e01edd2c7748d14c923d4d7e6d7c61b229e9c5a27eced3d9, size=65)], # nopep8
['n', util.num2bytes(0x1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED, size=32)], # nopep8
['q', vk.to_bytes()],
])
|
[
"def",
"keygrip_curve25519",
"(",
"vk",
")",
":",
"# pylint: disable=line-too-long",
"return",
"_compute_keygrip",
"(",
"[",
"[",
"'p'",
",",
"util",
".",
"num2bytes",
"(",
"0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED",
",",
"size",
"=",
"32",
")",
"]",
",",
"# nopep8",
"[",
"'a'",
",",
"b'\\x01\\xDB\\x41'",
"]",
",",
"[",
"'b'",
",",
"b'\\x01'",
"]",
",",
"[",
"'g'",
",",
"util",
".",
"num2bytes",
"(",
"0x04000000000000000000000000000000000000000000000000000000000000000920ae19a1b8a086b4e01edd2c7748d14c923d4d7e6d7c61b229e9c5a27eced3d9",
",",
"size",
"=",
"65",
")",
"]",
",",
"# nopep8",
"[",
"'n'",
",",
"util",
".",
"num2bytes",
"(",
"0x1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED",
",",
"size",
"=",
"32",
")",
"]",
",",
"# nopep8",
"[",
"'q'",
",",
"vk",
".",
"to_bytes",
"(",
")",
"]",
",",
"]",
")"
] |
Compute keygrip for Curve25519 public keys.
|
[
"Compute",
"keygrip",
"for",
"Curve25519",
"public",
"keys",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L138-L148
|
9,981
|
romanz/trezor-agent
|
libagent/gpg/protocol.py
|
get_curve_name_by_oid
|
def get_curve_name_by_oid(oid):
"""Return curve name matching specified OID, or raise KeyError."""
for curve_name, info in SUPPORTED_CURVES.items():
if info['oid'] == oid:
return curve_name
raise KeyError('Unknown OID: {!r}'.format(oid))
|
python
|
def get_curve_name_by_oid(oid):
"""Return curve name matching specified OID, or raise KeyError."""
for curve_name, info in SUPPORTED_CURVES.items():
if info['oid'] == oid:
return curve_name
raise KeyError('Unknown OID: {!r}'.format(oid))
|
[
"def",
"get_curve_name_by_oid",
"(",
"oid",
")",
":",
"for",
"curve_name",
",",
"info",
"in",
"SUPPORTED_CURVES",
".",
"items",
"(",
")",
":",
"if",
"info",
"[",
"'oid'",
"]",
"==",
"oid",
":",
"return",
"curve_name",
"raise",
"KeyError",
"(",
"'Unknown OID: {!r}'",
".",
"format",
"(",
"oid",
")",
")"
] |
Return curve name matching specified OID, or raise KeyError.
|
[
"Return",
"curve",
"name",
"matching",
"specified",
"OID",
"or",
"raise",
"KeyError",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L180-L185
|
9,982
|
romanz/trezor-agent
|
libagent/gpg/protocol.py
|
make_signature
|
def make_signature(signer_func, data_to_sign, public_algo,
hashed_subpackets, unhashed_subpackets, sig_type=0):
"""Create new GPG signature."""
# pylint: disable=too-many-arguments
header = struct.pack('>BBBB',
4, # version
sig_type, # rfc4880 (section-5.2.1)
public_algo,
8) # hash_alg (SHA256)
hashed = subpackets(*hashed_subpackets)
unhashed = subpackets(*unhashed_subpackets)
tail = b'\x04\xff' + struct.pack('>L', len(header) + len(hashed))
data_to_hash = data_to_sign + header + hashed + tail
log.debug('hashing %d bytes', len(data_to_hash))
digest = hashlib.sha256(data_to_hash).digest()
log.debug('signing digest: %s', util.hexlify(digest))
params = signer_func(digest=digest)
sig = b''.join(mpi(p) for p in params)
return bytes(header + hashed + unhashed +
digest[:2] + # used for decoder's sanity check
sig)
|
python
|
def make_signature(signer_func, data_to_sign, public_algo,
hashed_subpackets, unhashed_subpackets, sig_type=0):
"""Create new GPG signature."""
# pylint: disable=too-many-arguments
header = struct.pack('>BBBB',
4, # version
sig_type, # rfc4880 (section-5.2.1)
public_algo,
8) # hash_alg (SHA256)
hashed = subpackets(*hashed_subpackets)
unhashed = subpackets(*unhashed_subpackets)
tail = b'\x04\xff' + struct.pack('>L', len(header) + len(hashed))
data_to_hash = data_to_sign + header + hashed + tail
log.debug('hashing %d bytes', len(data_to_hash))
digest = hashlib.sha256(data_to_hash).digest()
log.debug('signing digest: %s', util.hexlify(digest))
params = signer_func(digest=digest)
sig = b''.join(mpi(p) for p in params)
return bytes(header + hashed + unhashed +
digest[:2] + # used for decoder's sanity check
sig)
|
[
"def",
"make_signature",
"(",
"signer_func",
",",
"data_to_sign",
",",
"public_algo",
",",
"hashed_subpackets",
",",
"unhashed_subpackets",
",",
"sig_type",
"=",
"0",
")",
":",
"# pylint: disable=too-many-arguments",
"header",
"=",
"struct",
".",
"pack",
"(",
"'>BBBB'",
",",
"4",
",",
"# version",
"sig_type",
",",
"# rfc4880 (section-5.2.1)",
"public_algo",
",",
"8",
")",
"# hash_alg (SHA256)",
"hashed",
"=",
"subpackets",
"(",
"*",
"hashed_subpackets",
")",
"unhashed",
"=",
"subpackets",
"(",
"*",
"unhashed_subpackets",
")",
"tail",
"=",
"b'\\x04\\xff'",
"+",
"struct",
".",
"pack",
"(",
"'>L'",
",",
"len",
"(",
"header",
")",
"+",
"len",
"(",
"hashed",
")",
")",
"data_to_hash",
"=",
"data_to_sign",
"+",
"header",
"+",
"hashed",
"+",
"tail",
"log",
".",
"debug",
"(",
"'hashing %d bytes'",
",",
"len",
"(",
"data_to_hash",
")",
")",
"digest",
"=",
"hashlib",
".",
"sha256",
"(",
"data_to_hash",
")",
".",
"digest",
"(",
")",
"log",
".",
"debug",
"(",
"'signing digest: %s'",
",",
"util",
".",
"hexlify",
"(",
"digest",
")",
")",
"params",
"=",
"signer_func",
"(",
"digest",
"=",
"digest",
")",
"sig",
"=",
"b''",
".",
"join",
"(",
"mpi",
"(",
"p",
")",
"for",
"p",
"in",
"params",
")",
"return",
"bytes",
"(",
"header",
"+",
"hashed",
"+",
"unhashed",
"+",
"digest",
"[",
":",
"2",
"]",
"+",
"# used for decoder's sanity check",
"sig",
")"
] |
Create new GPG signature.
|
[
"Create",
"new",
"GPG",
"signature",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L254-L276
|
9,983
|
romanz/trezor-agent
|
libagent/gpg/protocol.py
|
PublicKey.data
|
def data(self):
"""Data for packet creation."""
header = struct.pack('>BLB',
4, # version
self.created, # creation
self.algo_id) # public key algorithm ID
oid = util.prefix_len('>B', self.curve_info['oid'])
blob = self.curve_info['serialize'](self.verifying_key)
return header + oid + blob + self.ecdh_packet
|
python
|
def data(self):
"""Data for packet creation."""
header = struct.pack('>BLB',
4, # version
self.created, # creation
self.algo_id) # public key algorithm ID
oid = util.prefix_len('>B', self.curve_info['oid'])
blob = self.curve_info['serialize'](self.verifying_key)
return header + oid + blob + self.ecdh_packet
|
[
"def",
"data",
"(",
"self",
")",
":",
"header",
"=",
"struct",
".",
"pack",
"(",
"'>BLB'",
",",
"4",
",",
"# version",
"self",
".",
"created",
",",
"# creation",
"self",
".",
"algo_id",
")",
"# public key algorithm ID",
"oid",
"=",
"util",
".",
"prefix_len",
"(",
"'>B'",
",",
"self",
".",
"curve_info",
"[",
"'oid'",
"]",
")",
"blob",
"=",
"self",
".",
"curve_info",
"[",
"'serialize'",
"]",
"(",
"self",
".",
"verifying_key",
")",
"return",
"header",
"+",
"oid",
"+",
"blob",
"+",
"self",
".",
"ecdh_packet"
] |
Data for packet creation.
|
[
"Data",
"for",
"packet",
"creation",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L209-L217
|
9,984
|
romanz/trezor-agent
|
libagent/gpg/encode.py
|
create_subkey
|
def create_subkey(primary_bytes, subkey, signer_func, secret_bytes=b''):
"""Export new subkey to GPG primary key."""
subkey_packet = protocol.packet(tag=(7 if secret_bytes else 14),
blob=(subkey.data() + secret_bytes))
packets = list(decode.parse_packets(io.BytesIO(primary_bytes)))
primary, user_id, signature = packets[:3]
data_to_sign = primary['_to_hash'] + subkey.data_to_hash()
if subkey.ecdh:
embedded_sig = None
else:
# Primary Key Binding Signature
hashed_subpackets = [
protocol.subpacket_time(subkey.created)] # signature time
unhashed_subpackets = [
protocol.subpacket(16, subkey.key_id())] # issuer key id
embedded_sig = protocol.make_signature(
signer_func=signer_func,
data_to_sign=data_to_sign,
public_algo=subkey.algo_id,
sig_type=0x19,
hashed_subpackets=hashed_subpackets,
unhashed_subpackets=unhashed_subpackets)
# Subkey Binding Signature
# Key flags: https://tools.ietf.org/html/rfc4880#section-5.2.3.21
# (certify & sign) (encrypt)
flags = (2) if (not subkey.ecdh) else (4 | 8)
hashed_subpackets = [
protocol.subpacket_time(subkey.created), # signature time
protocol.subpacket_byte(0x1B, flags)]
unhashed_subpackets = []
unhashed_subpackets.append(protocol.subpacket(16, primary['key_id']))
if embedded_sig is not None:
unhashed_subpackets.append(protocol.subpacket(32, embedded_sig))
unhashed_subpackets.append(protocol.CUSTOM_SUBPACKET)
if not decode.has_custom_subpacket(signature):
signer_func = keyring.create_agent_signer(user_id['value'])
signature = protocol.make_signature(
signer_func=signer_func,
data_to_sign=data_to_sign,
public_algo=primary['algo'],
sig_type=0x18,
hashed_subpackets=hashed_subpackets,
unhashed_subpackets=unhashed_subpackets)
sign_packet = protocol.packet(tag=2, blob=signature)
return primary_bytes + subkey_packet + sign_packet
|
python
|
def create_subkey(primary_bytes, subkey, signer_func, secret_bytes=b''):
"""Export new subkey to GPG primary key."""
subkey_packet = protocol.packet(tag=(7 if secret_bytes else 14),
blob=(subkey.data() + secret_bytes))
packets = list(decode.parse_packets(io.BytesIO(primary_bytes)))
primary, user_id, signature = packets[:3]
data_to_sign = primary['_to_hash'] + subkey.data_to_hash()
if subkey.ecdh:
embedded_sig = None
else:
# Primary Key Binding Signature
hashed_subpackets = [
protocol.subpacket_time(subkey.created)] # signature time
unhashed_subpackets = [
protocol.subpacket(16, subkey.key_id())] # issuer key id
embedded_sig = protocol.make_signature(
signer_func=signer_func,
data_to_sign=data_to_sign,
public_algo=subkey.algo_id,
sig_type=0x19,
hashed_subpackets=hashed_subpackets,
unhashed_subpackets=unhashed_subpackets)
# Subkey Binding Signature
# Key flags: https://tools.ietf.org/html/rfc4880#section-5.2.3.21
# (certify & sign) (encrypt)
flags = (2) if (not subkey.ecdh) else (4 | 8)
hashed_subpackets = [
protocol.subpacket_time(subkey.created), # signature time
protocol.subpacket_byte(0x1B, flags)]
unhashed_subpackets = []
unhashed_subpackets.append(protocol.subpacket(16, primary['key_id']))
if embedded_sig is not None:
unhashed_subpackets.append(protocol.subpacket(32, embedded_sig))
unhashed_subpackets.append(protocol.CUSTOM_SUBPACKET)
if not decode.has_custom_subpacket(signature):
signer_func = keyring.create_agent_signer(user_id['value'])
signature = protocol.make_signature(
signer_func=signer_func,
data_to_sign=data_to_sign,
public_algo=primary['algo'],
sig_type=0x18,
hashed_subpackets=hashed_subpackets,
unhashed_subpackets=unhashed_subpackets)
sign_packet = protocol.packet(tag=2, blob=signature)
return primary_bytes + subkey_packet + sign_packet
|
[
"def",
"create_subkey",
"(",
"primary_bytes",
",",
"subkey",
",",
"signer_func",
",",
"secret_bytes",
"=",
"b''",
")",
":",
"subkey_packet",
"=",
"protocol",
".",
"packet",
"(",
"tag",
"=",
"(",
"7",
"if",
"secret_bytes",
"else",
"14",
")",
",",
"blob",
"=",
"(",
"subkey",
".",
"data",
"(",
")",
"+",
"secret_bytes",
")",
")",
"packets",
"=",
"list",
"(",
"decode",
".",
"parse_packets",
"(",
"io",
".",
"BytesIO",
"(",
"primary_bytes",
")",
")",
")",
"primary",
",",
"user_id",
",",
"signature",
"=",
"packets",
"[",
":",
"3",
"]",
"data_to_sign",
"=",
"primary",
"[",
"'_to_hash'",
"]",
"+",
"subkey",
".",
"data_to_hash",
"(",
")",
"if",
"subkey",
".",
"ecdh",
":",
"embedded_sig",
"=",
"None",
"else",
":",
"# Primary Key Binding Signature",
"hashed_subpackets",
"=",
"[",
"protocol",
".",
"subpacket_time",
"(",
"subkey",
".",
"created",
")",
"]",
"# signature time",
"unhashed_subpackets",
"=",
"[",
"protocol",
".",
"subpacket",
"(",
"16",
",",
"subkey",
".",
"key_id",
"(",
")",
")",
"]",
"# issuer key id",
"embedded_sig",
"=",
"protocol",
".",
"make_signature",
"(",
"signer_func",
"=",
"signer_func",
",",
"data_to_sign",
"=",
"data_to_sign",
",",
"public_algo",
"=",
"subkey",
".",
"algo_id",
",",
"sig_type",
"=",
"0x19",
",",
"hashed_subpackets",
"=",
"hashed_subpackets",
",",
"unhashed_subpackets",
"=",
"unhashed_subpackets",
")",
"# Subkey Binding Signature",
"# Key flags: https://tools.ietf.org/html/rfc4880#section-5.2.3.21",
"# (certify & sign) (encrypt)",
"flags",
"=",
"(",
"2",
")",
"if",
"(",
"not",
"subkey",
".",
"ecdh",
")",
"else",
"(",
"4",
"|",
"8",
")",
"hashed_subpackets",
"=",
"[",
"protocol",
".",
"subpacket_time",
"(",
"subkey",
".",
"created",
")",
",",
"# signature time",
"protocol",
".",
"subpacket_byte",
"(",
"0x1B",
",",
"flags",
")",
"]",
"unhashed_subpackets",
"=",
"[",
"]",
"unhashed_subpackets",
".",
"append",
"(",
"protocol",
".",
"subpacket",
"(",
"16",
",",
"primary",
"[",
"'key_id'",
"]",
")",
")",
"if",
"embedded_sig",
"is",
"not",
"None",
":",
"unhashed_subpackets",
".",
"append",
"(",
"protocol",
".",
"subpacket",
"(",
"32",
",",
"embedded_sig",
")",
")",
"unhashed_subpackets",
".",
"append",
"(",
"protocol",
".",
"CUSTOM_SUBPACKET",
")",
"if",
"not",
"decode",
".",
"has_custom_subpacket",
"(",
"signature",
")",
":",
"signer_func",
"=",
"keyring",
".",
"create_agent_signer",
"(",
"user_id",
"[",
"'value'",
"]",
")",
"signature",
"=",
"protocol",
".",
"make_signature",
"(",
"signer_func",
"=",
"signer_func",
",",
"data_to_sign",
"=",
"data_to_sign",
",",
"public_algo",
"=",
"primary",
"[",
"'algo'",
"]",
",",
"sig_type",
"=",
"0x18",
",",
"hashed_subpackets",
"=",
"hashed_subpackets",
",",
"unhashed_subpackets",
"=",
"unhashed_subpackets",
")",
"sign_packet",
"=",
"protocol",
".",
"packet",
"(",
"tag",
"=",
"2",
",",
"blob",
"=",
"signature",
")",
"return",
"primary_bytes",
"+",
"subkey_packet",
"+",
"sign_packet"
] |
Export new subkey to GPG primary key.
|
[
"Export",
"new",
"subkey",
"to",
"GPG",
"primary",
"key",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/encode.py#L51-L103
|
9,985
|
romanz/trezor-agent
|
libagent/gpg/__init__.py
|
verify_gpg_version
|
def verify_gpg_version():
"""Make sure that the installed GnuPG is not too old."""
existing_gpg = keyring.gpg_version().decode('ascii')
required_gpg = '>=2.1.11'
msg = 'Existing GnuPG has version "{}" ({} required)'.format(existing_gpg,
required_gpg)
if not semver.match(existing_gpg, required_gpg):
log.error(msg)
|
python
|
def verify_gpg_version():
"""Make sure that the installed GnuPG is not too old."""
existing_gpg = keyring.gpg_version().decode('ascii')
required_gpg = '>=2.1.11'
msg = 'Existing GnuPG has version "{}" ({} required)'.format(existing_gpg,
required_gpg)
if not semver.match(existing_gpg, required_gpg):
log.error(msg)
|
[
"def",
"verify_gpg_version",
"(",
")",
":",
"existing_gpg",
"=",
"keyring",
".",
"gpg_version",
"(",
")",
".",
"decode",
"(",
"'ascii'",
")",
"required_gpg",
"=",
"'>=2.1.11'",
"msg",
"=",
"'Existing GnuPG has version \"{}\" ({} required)'",
".",
"format",
"(",
"existing_gpg",
",",
"required_gpg",
")",
"if",
"not",
"semver",
".",
"match",
"(",
"existing_gpg",
",",
"required_gpg",
")",
":",
"log",
".",
"error",
"(",
"msg",
")"
] |
Make sure that the installed GnuPG is not too old.
|
[
"Make",
"sure",
"that",
"the",
"installed",
"GnuPG",
"is",
"not",
"too",
"old",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/__init__.py#L83-L90
|
9,986
|
romanz/trezor-agent
|
libagent/gpg/__init__.py
|
check_output
|
def check_output(args):
"""Runs command and returns the output as string."""
log.debug('run: %s', args)
out = subprocess.check_output(args=args).decode('utf-8')
log.debug('out: %r', out)
return out
|
python
|
def check_output(args):
"""Runs command and returns the output as string."""
log.debug('run: %s', args)
out = subprocess.check_output(args=args).decode('utf-8')
log.debug('out: %r', out)
return out
|
[
"def",
"check_output",
"(",
"args",
")",
":",
"log",
".",
"debug",
"(",
"'run: %s'",
",",
"args",
")",
"out",
"=",
"subprocess",
".",
"check_output",
"(",
"args",
"=",
"args",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"log",
".",
"debug",
"(",
"'out: %r'",
",",
"out",
")",
"return",
"out"
] |
Runs command and returns the output as string.
|
[
"Runs",
"command",
"and",
"returns",
"the",
"output",
"as",
"string",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/__init__.py#L93-L98
|
9,987
|
romanz/trezor-agent
|
libagent/gpg/__init__.py
|
check_call
|
def check_call(args, stdin=None, env=None):
"""Runs command and verifies its success."""
log.debug('run: %s%s', args, ' {}'.format(env) if env else '')
subprocess.check_call(args=args, stdin=stdin, env=env)
|
python
|
def check_call(args, stdin=None, env=None):
"""Runs command and verifies its success."""
log.debug('run: %s%s', args, ' {}'.format(env) if env else '')
subprocess.check_call(args=args, stdin=stdin, env=env)
|
[
"def",
"check_call",
"(",
"args",
",",
"stdin",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'run: %s%s'",
",",
"args",
",",
"' {}'",
".",
"format",
"(",
"env",
")",
"if",
"env",
"else",
"''",
")",
"subprocess",
".",
"check_call",
"(",
"args",
"=",
"args",
",",
"stdin",
"=",
"stdin",
",",
"env",
"=",
"env",
")"
] |
Runs command and verifies its success.
|
[
"Runs",
"command",
"and",
"verifies",
"its",
"success",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/__init__.py#L101-L104
|
9,988
|
romanz/trezor-agent
|
libagent/gpg/__init__.py
|
write_file
|
def write_file(path, data):
"""Writes data to specified path."""
with open(path, 'w') as f:
log.debug('setting %s contents:\n%s', path, data)
f.write(data)
return f
|
python
|
def write_file(path, data):
"""Writes data to specified path."""
with open(path, 'w') as f:
log.debug('setting %s contents:\n%s', path, data)
f.write(data)
return f
|
[
"def",
"write_file",
"(",
"path",
",",
"data",
")",
":",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"log",
".",
"debug",
"(",
"'setting %s contents:\\n%s'",
",",
"path",
",",
"data",
")",
"f",
".",
"write",
"(",
"data",
")",
"return",
"f"
] |
Writes data to specified path.
|
[
"Writes",
"data",
"to",
"specified",
"path",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/__init__.py#L107-L112
|
9,989
|
romanz/trezor-agent
|
libagent/gpg/__init__.py
|
run_agent
|
def run_agent(device_type):
"""Run a simple GPG-agent server."""
p = argparse.ArgumentParser()
p.add_argument('--homedir', default=os.environ.get('GNUPGHOME'))
p.add_argument('-v', '--verbose', default=0, action='count')
p.add_argument('--server', default=False, action='store_true',
help='Use stdin/stdout for communication with GPG.')
p.add_argument('--pin-entry-binary', type=str, default='pinentry',
help='Path to PIN entry UI helper.')
p.add_argument('--passphrase-entry-binary', type=str, default='pinentry',
help='Path to passphrase entry UI helper.')
p.add_argument('--cache-expiry-seconds', type=float, default=float('inf'),
help='Expire passphrase from cache after this duration.')
args, _ = p.parse_known_args()
assert args.homedir
log_file = os.path.join(args.homedir, 'gpg-agent.log')
util.setup_logging(verbosity=args.verbose, filename=log_file)
log.debug('sys.argv: %s', sys.argv)
log.debug('os.environ: %s', os.environ)
log.debug('pid: %d, parent pid: %d', os.getpid(), os.getppid())
try:
env = {'GNUPGHOME': args.homedir, 'PATH': os.environ['PATH']}
pubkey_bytes = keyring.export_public_keys(env=env)
device_type.ui = device.ui.UI(device_type=device_type,
config=vars(args))
device_type.ui.cached_passphrase_ack = util.ExpiringCache(
seconds=float(args.cache_expiry_seconds))
handler = agent.Handler(device=device_type(),
pubkey_bytes=pubkey_bytes)
sock_server = _server_from_assuan_fd(os.environ)
if sock_server is None:
sock_server = _server_from_sock_path(env)
with sock_server as sock:
for conn in agent.yield_connections(sock):
with contextlib.closing(conn):
try:
handler.handle(conn)
except agent.AgentStop:
log.info('stopping gpg-agent')
return
except IOError as e:
log.info('connection closed: %s', e)
return
except Exception as e: # pylint: disable=broad-except
log.exception('handler failed: %s', e)
except Exception as e: # pylint: disable=broad-except
log.exception('gpg-agent failed: %s', e)
|
python
|
def run_agent(device_type):
"""Run a simple GPG-agent server."""
p = argparse.ArgumentParser()
p.add_argument('--homedir', default=os.environ.get('GNUPGHOME'))
p.add_argument('-v', '--verbose', default=0, action='count')
p.add_argument('--server', default=False, action='store_true',
help='Use stdin/stdout for communication with GPG.')
p.add_argument('--pin-entry-binary', type=str, default='pinentry',
help='Path to PIN entry UI helper.')
p.add_argument('--passphrase-entry-binary', type=str, default='pinentry',
help='Path to passphrase entry UI helper.')
p.add_argument('--cache-expiry-seconds', type=float, default=float('inf'),
help='Expire passphrase from cache after this duration.')
args, _ = p.parse_known_args()
assert args.homedir
log_file = os.path.join(args.homedir, 'gpg-agent.log')
util.setup_logging(verbosity=args.verbose, filename=log_file)
log.debug('sys.argv: %s', sys.argv)
log.debug('os.environ: %s', os.environ)
log.debug('pid: %d, parent pid: %d', os.getpid(), os.getppid())
try:
env = {'GNUPGHOME': args.homedir, 'PATH': os.environ['PATH']}
pubkey_bytes = keyring.export_public_keys(env=env)
device_type.ui = device.ui.UI(device_type=device_type,
config=vars(args))
device_type.ui.cached_passphrase_ack = util.ExpiringCache(
seconds=float(args.cache_expiry_seconds))
handler = agent.Handler(device=device_type(),
pubkey_bytes=pubkey_bytes)
sock_server = _server_from_assuan_fd(os.environ)
if sock_server is None:
sock_server = _server_from_sock_path(env)
with sock_server as sock:
for conn in agent.yield_connections(sock):
with contextlib.closing(conn):
try:
handler.handle(conn)
except agent.AgentStop:
log.info('stopping gpg-agent')
return
except IOError as e:
log.info('connection closed: %s', e)
return
except Exception as e: # pylint: disable=broad-except
log.exception('handler failed: %s', e)
except Exception as e: # pylint: disable=broad-except
log.exception('gpg-agent failed: %s', e)
|
[
"def",
"run_agent",
"(",
"device_type",
")",
":",
"p",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"p",
".",
"add_argument",
"(",
"'--homedir'",
",",
"default",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'GNUPGHOME'",
")",
")",
"p",
".",
"add_argument",
"(",
"'-v'",
",",
"'--verbose'",
",",
"default",
"=",
"0",
",",
"action",
"=",
"'count'",
")",
"p",
".",
"add_argument",
"(",
"'--server'",
",",
"default",
"=",
"False",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'Use stdin/stdout for communication with GPG.'",
")",
"p",
".",
"add_argument",
"(",
"'--pin-entry-binary'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'pinentry'",
",",
"help",
"=",
"'Path to PIN entry UI helper.'",
")",
"p",
".",
"add_argument",
"(",
"'--passphrase-entry-binary'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'pinentry'",
",",
"help",
"=",
"'Path to passphrase entry UI helper.'",
")",
"p",
".",
"add_argument",
"(",
"'--cache-expiry-seconds'",
",",
"type",
"=",
"float",
",",
"default",
"=",
"float",
"(",
"'inf'",
")",
",",
"help",
"=",
"'Expire passphrase from cache after this duration.'",
")",
"args",
",",
"_",
"=",
"p",
".",
"parse_known_args",
"(",
")",
"assert",
"args",
".",
"homedir",
"log_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"homedir",
",",
"'gpg-agent.log'",
")",
"util",
".",
"setup_logging",
"(",
"verbosity",
"=",
"args",
".",
"verbose",
",",
"filename",
"=",
"log_file",
")",
"log",
".",
"debug",
"(",
"'sys.argv: %s'",
",",
"sys",
".",
"argv",
")",
"log",
".",
"debug",
"(",
"'os.environ: %s'",
",",
"os",
".",
"environ",
")",
"log",
".",
"debug",
"(",
"'pid: %d, parent pid: %d'",
",",
"os",
".",
"getpid",
"(",
")",
",",
"os",
".",
"getppid",
"(",
")",
")",
"try",
":",
"env",
"=",
"{",
"'GNUPGHOME'",
":",
"args",
".",
"homedir",
",",
"'PATH'",
":",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
"}",
"pubkey_bytes",
"=",
"keyring",
".",
"export_public_keys",
"(",
"env",
"=",
"env",
")",
"device_type",
".",
"ui",
"=",
"device",
".",
"ui",
".",
"UI",
"(",
"device_type",
"=",
"device_type",
",",
"config",
"=",
"vars",
"(",
"args",
")",
")",
"device_type",
".",
"ui",
".",
"cached_passphrase_ack",
"=",
"util",
".",
"ExpiringCache",
"(",
"seconds",
"=",
"float",
"(",
"args",
".",
"cache_expiry_seconds",
")",
")",
"handler",
"=",
"agent",
".",
"Handler",
"(",
"device",
"=",
"device_type",
"(",
")",
",",
"pubkey_bytes",
"=",
"pubkey_bytes",
")",
"sock_server",
"=",
"_server_from_assuan_fd",
"(",
"os",
".",
"environ",
")",
"if",
"sock_server",
"is",
"None",
":",
"sock_server",
"=",
"_server_from_sock_path",
"(",
"env",
")",
"with",
"sock_server",
"as",
"sock",
":",
"for",
"conn",
"in",
"agent",
".",
"yield_connections",
"(",
"sock",
")",
":",
"with",
"contextlib",
".",
"closing",
"(",
"conn",
")",
":",
"try",
":",
"handler",
".",
"handle",
"(",
"conn",
")",
"except",
"agent",
".",
"AgentStop",
":",
"log",
".",
"info",
"(",
"'stopping gpg-agent'",
")",
"return",
"except",
"IOError",
"as",
"e",
":",
"log",
".",
"info",
"(",
"'connection closed: %s'",
",",
"e",
")",
"return",
"except",
"Exception",
"as",
"e",
":",
"# pylint: disable=broad-except",
"log",
".",
"exception",
"(",
"'handler failed: %s'",
",",
"e",
")",
"except",
"Exception",
"as",
"e",
":",
"# pylint: disable=broad-except",
"log",
".",
"exception",
"(",
"'gpg-agent failed: %s'",
",",
"e",
")"
] |
Run a simple GPG-agent server.
|
[
"Run",
"a",
"simple",
"GPG",
"-",
"agent",
"server",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/__init__.py#L222-L276
|
9,990
|
romanz/trezor-agent
|
libagent/device/trezor_defs.py
|
find_device
|
def find_device():
"""Selects a transport based on `TREZOR_PATH` environment variable.
If unset, picks first connected device.
"""
try:
return get_transport(os.environ.get("TREZOR_PATH"))
except Exception as e: # pylint: disable=broad-except
log.debug("Failed to find a Trezor device: %s", e)
|
python
|
def find_device():
"""Selects a transport based on `TREZOR_PATH` environment variable.
If unset, picks first connected device.
"""
try:
return get_transport(os.environ.get("TREZOR_PATH"))
except Exception as e: # pylint: disable=broad-except
log.debug("Failed to find a Trezor device: %s", e)
|
[
"def",
"find_device",
"(",
")",
":",
"try",
":",
"return",
"get_transport",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"\"TREZOR_PATH\"",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"# pylint: disable=broad-except",
"log",
".",
"debug",
"(",
"\"Failed to find a Trezor device: %s\"",
",",
"e",
")"
] |
Selects a transport based on `TREZOR_PATH` environment variable.
If unset, picks first connected device.
|
[
"Selects",
"a",
"transport",
"based",
"on",
"TREZOR_PATH",
"environment",
"variable",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/trezor_defs.py#L22-L30
|
9,991
|
romanz/trezor-agent
|
libagent/device/ledger.py
|
_convert_public_key
|
def _convert_public_key(ecdsa_curve_name, result):
"""Convert Ledger reply into PublicKey object."""
if ecdsa_curve_name == 'nist256p1':
if (result[64] & 1) != 0:
result = bytearray([0x03]) + result[1:33]
else:
result = bytearray([0x02]) + result[1:33]
else:
result = result[1:]
keyX = bytearray(result[0:32])
keyY = bytearray(result[32:][::-1])
if (keyX[31] & 1) != 0:
keyY[31] |= 0x80
result = b'\x00' + bytes(keyY)
return bytes(result)
|
python
|
def _convert_public_key(ecdsa_curve_name, result):
"""Convert Ledger reply into PublicKey object."""
if ecdsa_curve_name == 'nist256p1':
if (result[64] & 1) != 0:
result = bytearray([0x03]) + result[1:33]
else:
result = bytearray([0x02]) + result[1:33]
else:
result = result[1:]
keyX = bytearray(result[0:32])
keyY = bytearray(result[32:][::-1])
if (keyX[31] & 1) != 0:
keyY[31] |= 0x80
result = b'\x00' + bytes(keyY)
return bytes(result)
|
[
"def",
"_convert_public_key",
"(",
"ecdsa_curve_name",
",",
"result",
")",
":",
"if",
"ecdsa_curve_name",
"==",
"'nist256p1'",
":",
"if",
"(",
"result",
"[",
"64",
"]",
"&",
"1",
")",
"!=",
"0",
":",
"result",
"=",
"bytearray",
"(",
"[",
"0x03",
"]",
")",
"+",
"result",
"[",
"1",
":",
"33",
"]",
"else",
":",
"result",
"=",
"bytearray",
"(",
"[",
"0x02",
"]",
")",
"+",
"result",
"[",
"1",
":",
"33",
"]",
"else",
":",
"result",
"=",
"result",
"[",
"1",
":",
"]",
"keyX",
"=",
"bytearray",
"(",
"result",
"[",
"0",
":",
"32",
"]",
")",
"keyY",
"=",
"bytearray",
"(",
"result",
"[",
"32",
":",
"]",
"[",
":",
":",
"-",
"1",
"]",
")",
"if",
"(",
"keyX",
"[",
"31",
"]",
"&",
"1",
")",
"!=",
"0",
":",
"keyY",
"[",
"31",
"]",
"|=",
"0x80",
"result",
"=",
"b'\\x00'",
"+",
"bytes",
"(",
"keyY",
")",
"return",
"bytes",
"(",
"result",
")"
] |
Convert Ledger reply into PublicKey object.
|
[
"Convert",
"Ledger",
"reply",
"into",
"PublicKey",
"object",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/ledger.py#L19-L33
|
9,992
|
romanz/trezor-agent
|
libagent/device/ledger.py
|
LedgerNanoS.connect
|
def connect(self):
"""Enumerate and connect to the first USB HID interface."""
try:
return comm.getDongle()
except comm.CommException as e:
raise interface.NotFoundError(
'{} not connected: "{}"'.format(self, e))
|
python
|
def connect(self):
"""Enumerate and connect to the first USB HID interface."""
try:
return comm.getDongle()
except comm.CommException as e:
raise interface.NotFoundError(
'{} not connected: "{}"'.format(self, e))
|
[
"def",
"connect",
"(",
"self",
")",
":",
"try",
":",
"return",
"comm",
".",
"getDongle",
"(",
")",
"except",
"comm",
".",
"CommException",
"as",
"e",
":",
"raise",
"interface",
".",
"NotFoundError",
"(",
"'{} not connected: \"{}\"'",
".",
"format",
"(",
"self",
",",
"e",
")",
")"
] |
Enumerate and connect to the first USB HID interface.
|
[
"Enumerate",
"and",
"connect",
"to",
"the",
"first",
"USB",
"HID",
"interface",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/ledger.py#L44-L50
|
9,993
|
romanz/trezor-agent
|
libagent/device/ledger.py
|
LedgerNanoS.pubkey
|
def pubkey(self, identity, ecdh=False):
"""Get PublicKey object for specified BIP32 address and elliptic curve."""
curve_name = identity.get_curve_name(ecdh)
path = _expand_path(identity.get_bip32_address(ecdh))
if curve_name == 'nist256p1':
p2 = '01'
else:
p2 = '02'
apdu = '800200' + p2
apdu = binascii.unhexlify(apdu)
apdu += bytearray([len(path) + 1, len(path) // 4])
apdu += path
log.debug('apdu: %r', apdu)
result = bytearray(self.conn.exchange(bytes(apdu)))
log.debug('result: %r', result)
return _convert_public_key(curve_name, result[1:])
|
python
|
def pubkey(self, identity, ecdh=False):
"""Get PublicKey object for specified BIP32 address and elliptic curve."""
curve_name = identity.get_curve_name(ecdh)
path = _expand_path(identity.get_bip32_address(ecdh))
if curve_name == 'nist256p1':
p2 = '01'
else:
p2 = '02'
apdu = '800200' + p2
apdu = binascii.unhexlify(apdu)
apdu += bytearray([len(path) + 1, len(path) // 4])
apdu += path
log.debug('apdu: %r', apdu)
result = bytearray(self.conn.exchange(bytes(apdu)))
log.debug('result: %r', result)
return _convert_public_key(curve_name, result[1:])
|
[
"def",
"pubkey",
"(",
"self",
",",
"identity",
",",
"ecdh",
"=",
"False",
")",
":",
"curve_name",
"=",
"identity",
".",
"get_curve_name",
"(",
"ecdh",
")",
"path",
"=",
"_expand_path",
"(",
"identity",
".",
"get_bip32_address",
"(",
"ecdh",
")",
")",
"if",
"curve_name",
"==",
"'nist256p1'",
":",
"p2",
"=",
"'01'",
"else",
":",
"p2",
"=",
"'02'",
"apdu",
"=",
"'800200'",
"+",
"p2",
"apdu",
"=",
"binascii",
".",
"unhexlify",
"(",
"apdu",
")",
"apdu",
"+=",
"bytearray",
"(",
"[",
"len",
"(",
"path",
")",
"+",
"1",
",",
"len",
"(",
"path",
")",
"//",
"4",
"]",
")",
"apdu",
"+=",
"path",
"log",
".",
"debug",
"(",
"'apdu: %r'",
",",
"apdu",
")",
"result",
"=",
"bytearray",
"(",
"self",
".",
"conn",
".",
"exchange",
"(",
"bytes",
"(",
"apdu",
")",
")",
")",
"log",
".",
"debug",
"(",
"'result: %r'",
",",
"result",
")",
"return",
"_convert_public_key",
"(",
"curve_name",
",",
"result",
"[",
"1",
":",
"]",
")"
] |
Get PublicKey object for specified BIP32 address and elliptic curve.
|
[
"Get",
"PublicKey",
"object",
"for",
"specified",
"BIP32",
"address",
"and",
"elliptic",
"curve",
"."
] |
513b1259c4d7aca5f88cd958edc11828d0712f1b
|
https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/ledger.py#L52-L67
|
9,994
|
inonit/drf-haystack
|
ez_setup.py
|
download_setuptools
|
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15):
"""Download distribute from a specified location and return its filename
`version` should be a valid distribute version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download
attempt.
"""
# making sure we use the absolute path
to_dir = os.path.abspath(to_dir)
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
tgz_name = "distribute-%s.tar.gz" % version
url = download_base + tgz_name
saveto = os.path.join(to_dir, tgz_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
log.warn("Downloading %s", url)
src = urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = src.read()
dst = open(saveto, "wb")
dst.write(data)
finally:
if src:
src.close()
if dst:
dst.close()
return os.path.realpath(saveto)
|
python
|
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15):
"""Download distribute from a specified location and return its filename
`version` should be a valid distribute version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download
attempt.
"""
# making sure we use the absolute path
to_dir = os.path.abspath(to_dir)
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
tgz_name = "distribute-%s.tar.gz" % version
url = download_base + tgz_name
saveto = os.path.join(to_dir, tgz_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
log.warn("Downloading %s", url)
src = urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = src.read()
dst = open(saveto, "wb")
dst.write(data)
finally:
if src:
src.close()
if dst:
dst.close()
return os.path.realpath(saveto)
|
[
"def",
"download_setuptools",
"(",
"version",
"=",
"DEFAULT_VERSION",
",",
"download_base",
"=",
"DEFAULT_URL",
",",
"to_dir",
"=",
"os",
".",
"curdir",
",",
"delay",
"=",
"15",
")",
":",
"# making sure we use the absolute path",
"to_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"to_dir",
")",
"try",
":",
"from",
"urllib",
".",
"request",
"import",
"urlopen",
"except",
"ImportError",
":",
"from",
"urllib2",
"import",
"urlopen",
"tgz_name",
"=",
"\"distribute-%s.tar.gz\"",
"%",
"version",
"url",
"=",
"download_base",
"+",
"tgz_name",
"saveto",
"=",
"os",
".",
"path",
".",
"join",
"(",
"to_dir",
",",
"tgz_name",
")",
"src",
"=",
"dst",
"=",
"None",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"saveto",
")",
":",
"# Avoid repeated downloads",
"try",
":",
"log",
".",
"warn",
"(",
"\"Downloading %s\"",
",",
"url",
")",
"src",
"=",
"urlopen",
"(",
"url",
")",
"# Read/write all in one block, so we don't create a corrupt file",
"# if the download is interrupted.",
"data",
"=",
"src",
".",
"read",
"(",
")",
"dst",
"=",
"open",
"(",
"saveto",
",",
"\"wb\"",
")",
"dst",
".",
"write",
"(",
"data",
")",
"finally",
":",
"if",
"src",
":",
"src",
".",
"close",
"(",
")",
"if",
"dst",
":",
"dst",
".",
"close",
"(",
")",
"return",
"os",
".",
"path",
".",
"realpath",
"(",
"saveto",
")"
] |
Download distribute from a specified location and return its filename
`version` should be a valid distribute version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download
attempt.
|
[
"Download",
"distribute",
"from",
"a",
"specified",
"location",
"and",
"return",
"its",
"filename"
] |
ceabd0f6318f129758341ab08292a20205d6f4cd
|
https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/ez_setup.py#L170-L204
|
9,995
|
inonit/drf-haystack
|
drf_haystack/query.py
|
BaseQueryBuilder.tokenize
|
def tokenize(stream, separator):
"""
Tokenize and yield query parameter values.
:param stream: Input value
:param separator: Character to use to separate the tokens.
:return:
"""
for value in stream:
for token in value.split(separator):
if token:
yield token.strip()
|
python
|
def tokenize(stream, separator):
"""
Tokenize and yield query parameter values.
:param stream: Input value
:param separator: Character to use to separate the tokens.
:return:
"""
for value in stream:
for token in value.split(separator):
if token:
yield token.strip()
|
[
"def",
"tokenize",
"(",
"stream",
",",
"separator",
")",
":",
"for",
"value",
"in",
"stream",
":",
"for",
"token",
"in",
"value",
".",
"split",
"(",
"separator",
")",
":",
"if",
"token",
":",
"yield",
"token",
".",
"strip",
"(",
")"
] |
Tokenize and yield query parameter values.
:param stream: Input value
:param separator: Character to use to separate the tokens.
:return:
|
[
"Tokenize",
"and",
"yield",
"query",
"parameter",
"values",
"."
] |
ceabd0f6318f129758341ab08292a20205d6f4cd
|
https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/query.py#L34-L45
|
9,996
|
inonit/drf-haystack
|
drf_haystack/query.py
|
FilterQueryBuilder.build_query
|
def build_query(self, **filters):
"""
Creates a single SQ filter from querystring parameters that correspond to the SearchIndex fields
that have been "registered" in `view.fields`.
Default behavior is to `OR` terms for the same parameters, and `AND` between parameters. Any
querystring parameters that are not registered in `view.fields` will be ignored.
:param dict[str, list[str]] filters: is an expanded QueryDict or a mapping of keys to a list of
parameters.
"""
applicable_filters = []
applicable_exclusions = []
for param, value in filters.items():
excluding_term = False
param_parts = param.split("__")
base_param = param_parts[0] # only test against field without lookup
negation_keyword = constants.DRF_HAYSTACK_NEGATION_KEYWORD
if len(param_parts) > 1 and param_parts[1] == negation_keyword:
excluding_term = True
param = param.replace("__%s" % negation_keyword, "") # haystack wouldn't understand our negation
if self.view.serializer_class:
if hasattr(self.view.serializer_class.Meta, 'field_aliases'):
old_base = base_param
base_param = self.view.serializer_class.Meta.field_aliases.get(base_param, base_param)
param = param.replace(old_base, base_param) # need to replace the alias
fields = getattr(self.view.serializer_class.Meta, 'fields', [])
exclude = getattr(self.view.serializer_class.Meta, 'exclude', [])
search_fields = getattr(self.view.serializer_class.Meta, 'search_fields', [])
# Skip if the parameter is not listed in the serializer's `fields`
# or if it's in the `exclude` list.
if ((fields or search_fields) and base_param not in
chain(fields, search_fields)) or base_param in exclude or not value:
continue
field_queries = []
if len(param_parts) > 1 and param_parts[-1] in ('in', 'range'):
# `in` and `range` filters expects a list of values
field_queries.append(self.view.query_object((param, list(self.tokenize(value, self.view.lookup_sep)))))
else:
for token in self.tokenize(value, self.view.lookup_sep):
field_queries.append(self.view.query_object((param, token)))
field_queries = [fq for fq in field_queries if fq]
if len(field_queries) > 0:
term = six.moves.reduce(operator.or_, field_queries)
if excluding_term:
applicable_exclusions.append(term)
else:
applicable_filters.append(term)
applicable_filters = six.moves.reduce(
self.default_operator, filter(lambda x: x, applicable_filters)) if applicable_filters else []
applicable_exclusions = six.moves.reduce(
self.default_operator, filter(lambda x: x, applicable_exclusions)) if applicable_exclusions else []
return applicable_filters, applicable_exclusions
|
python
|
def build_query(self, **filters):
"""
Creates a single SQ filter from querystring parameters that correspond to the SearchIndex fields
that have been "registered" in `view.fields`.
Default behavior is to `OR` terms for the same parameters, and `AND` between parameters. Any
querystring parameters that are not registered in `view.fields` will be ignored.
:param dict[str, list[str]] filters: is an expanded QueryDict or a mapping of keys to a list of
parameters.
"""
applicable_filters = []
applicable_exclusions = []
for param, value in filters.items():
excluding_term = False
param_parts = param.split("__")
base_param = param_parts[0] # only test against field without lookup
negation_keyword = constants.DRF_HAYSTACK_NEGATION_KEYWORD
if len(param_parts) > 1 and param_parts[1] == negation_keyword:
excluding_term = True
param = param.replace("__%s" % negation_keyword, "") # haystack wouldn't understand our negation
if self.view.serializer_class:
if hasattr(self.view.serializer_class.Meta, 'field_aliases'):
old_base = base_param
base_param = self.view.serializer_class.Meta.field_aliases.get(base_param, base_param)
param = param.replace(old_base, base_param) # need to replace the alias
fields = getattr(self.view.serializer_class.Meta, 'fields', [])
exclude = getattr(self.view.serializer_class.Meta, 'exclude', [])
search_fields = getattr(self.view.serializer_class.Meta, 'search_fields', [])
# Skip if the parameter is not listed in the serializer's `fields`
# or if it's in the `exclude` list.
if ((fields or search_fields) and base_param not in
chain(fields, search_fields)) or base_param in exclude or not value:
continue
field_queries = []
if len(param_parts) > 1 and param_parts[-1] in ('in', 'range'):
# `in` and `range` filters expects a list of values
field_queries.append(self.view.query_object((param, list(self.tokenize(value, self.view.lookup_sep)))))
else:
for token in self.tokenize(value, self.view.lookup_sep):
field_queries.append(self.view.query_object((param, token)))
field_queries = [fq for fq in field_queries if fq]
if len(field_queries) > 0:
term = six.moves.reduce(operator.or_, field_queries)
if excluding_term:
applicable_exclusions.append(term)
else:
applicable_filters.append(term)
applicable_filters = six.moves.reduce(
self.default_operator, filter(lambda x: x, applicable_filters)) if applicable_filters else []
applicable_exclusions = six.moves.reduce(
self.default_operator, filter(lambda x: x, applicable_exclusions)) if applicable_exclusions else []
return applicable_filters, applicable_exclusions
|
[
"def",
"build_query",
"(",
"self",
",",
"*",
"*",
"filters",
")",
":",
"applicable_filters",
"=",
"[",
"]",
"applicable_exclusions",
"=",
"[",
"]",
"for",
"param",
",",
"value",
"in",
"filters",
".",
"items",
"(",
")",
":",
"excluding_term",
"=",
"False",
"param_parts",
"=",
"param",
".",
"split",
"(",
"\"__\"",
")",
"base_param",
"=",
"param_parts",
"[",
"0",
"]",
"# only test against field without lookup",
"negation_keyword",
"=",
"constants",
".",
"DRF_HAYSTACK_NEGATION_KEYWORD",
"if",
"len",
"(",
"param_parts",
")",
">",
"1",
"and",
"param_parts",
"[",
"1",
"]",
"==",
"negation_keyword",
":",
"excluding_term",
"=",
"True",
"param",
"=",
"param",
".",
"replace",
"(",
"\"__%s\"",
"%",
"negation_keyword",
",",
"\"\"",
")",
"# haystack wouldn't understand our negation",
"if",
"self",
".",
"view",
".",
"serializer_class",
":",
"if",
"hasattr",
"(",
"self",
".",
"view",
".",
"serializer_class",
".",
"Meta",
",",
"'field_aliases'",
")",
":",
"old_base",
"=",
"base_param",
"base_param",
"=",
"self",
".",
"view",
".",
"serializer_class",
".",
"Meta",
".",
"field_aliases",
".",
"get",
"(",
"base_param",
",",
"base_param",
")",
"param",
"=",
"param",
".",
"replace",
"(",
"old_base",
",",
"base_param",
")",
"# need to replace the alias",
"fields",
"=",
"getattr",
"(",
"self",
".",
"view",
".",
"serializer_class",
".",
"Meta",
",",
"'fields'",
",",
"[",
"]",
")",
"exclude",
"=",
"getattr",
"(",
"self",
".",
"view",
".",
"serializer_class",
".",
"Meta",
",",
"'exclude'",
",",
"[",
"]",
")",
"search_fields",
"=",
"getattr",
"(",
"self",
".",
"view",
".",
"serializer_class",
".",
"Meta",
",",
"'search_fields'",
",",
"[",
"]",
")",
"# Skip if the parameter is not listed in the serializer's `fields`",
"# or if it's in the `exclude` list.",
"if",
"(",
"(",
"fields",
"or",
"search_fields",
")",
"and",
"base_param",
"not",
"in",
"chain",
"(",
"fields",
",",
"search_fields",
")",
")",
"or",
"base_param",
"in",
"exclude",
"or",
"not",
"value",
":",
"continue",
"field_queries",
"=",
"[",
"]",
"if",
"len",
"(",
"param_parts",
")",
">",
"1",
"and",
"param_parts",
"[",
"-",
"1",
"]",
"in",
"(",
"'in'",
",",
"'range'",
")",
":",
"# `in` and `range` filters expects a list of values",
"field_queries",
".",
"append",
"(",
"self",
".",
"view",
".",
"query_object",
"(",
"(",
"param",
",",
"list",
"(",
"self",
".",
"tokenize",
"(",
"value",
",",
"self",
".",
"view",
".",
"lookup_sep",
")",
")",
")",
")",
")",
"else",
":",
"for",
"token",
"in",
"self",
".",
"tokenize",
"(",
"value",
",",
"self",
".",
"view",
".",
"lookup_sep",
")",
":",
"field_queries",
".",
"append",
"(",
"self",
".",
"view",
".",
"query_object",
"(",
"(",
"param",
",",
"token",
")",
")",
")",
"field_queries",
"=",
"[",
"fq",
"for",
"fq",
"in",
"field_queries",
"if",
"fq",
"]",
"if",
"len",
"(",
"field_queries",
")",
">",
"0",
":",
"term",
"=",
"six",
".",
"moves",
".",
"reduce",
"(",
"operator",
".",
"or_",
",",
"field_queries",
")",
"if",
"excluding_term",
":",
"applicable_exclusions",
".",
"append",
"(",
"term",
")",
"else",
":",
"applicable_filters",
".",
"append",
"(",
"term",
")",
"applicable_filters",
"=",
"six",
".",
"moves",
".",
"reduce",
"(",
"self",
".",
"default_operator",
",",
"filter",
"(",
"lambda",
"x",
":",
"x",
",",
"applicable_filters",
")",
")",
"if",
"applicable_filters",
"else",
"[",
"]",
"applicable_exclusions",
"=",
"six",
".",
"moves",
".",
"reduce",
"(",
"self",
".",
"default_operator",
",",
"filter",
"(",
"lambda",
"x",
":",
"x",
",",
"applicable_exclusions",
")",
")",
"if",
"applicable_exclusions",
"else",
"[",
"]",
"return",
"applicable_filters",
",",
"applicable_exclusions"
] |
Creates a single SQ filter from querystring parameters that correspond to the SearchIndex fields
that have been "registered" in `view.fields`.
Default behavior is to `OR` terms for the same parameters, and `AND` between parameters. Any
querystring parameters that are not registered in `view.fields` will be ignored.
:param dict[str, list[str]] filters: is an expanded QueryDict or a mapping of keys to a list of
parameters.
|
[
"Creates",
"a",
"single",
"SQ",
"filter",
"from",
"querystring",
"parameters",
"that",
"correspond",
"to",
"the",
"SearchIndex",
"fields",
"that",
"have",
"been",
"registered",
"in",
"view",
".",
"fields",
"."
] |
ceabd0f6318f129758341ab08292a20205d6f4cd
|
https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/query.py#L89-L151
|
9,997
|
inonit/drf-haystack
|
drf_haystack/query.py
|
FacetQueryBuilder.build_query
|
def build_query(self, **filters):
"""
Creates a dict of dictionaries suitable for passing to the SearchQuerySet `facet`,
`date_facet` or `query_facet` method. All key word arguments should be wrapped in a list.
:param view: API View
:param dict[str, list[str]] filters: is an expanded QueryDict or a mapping
of keys to a list of parameters.
"""
field_facets = {}
date_facets = {}
query_facets = {}
facet_serializer_cls = self.view.get_facet_serializer_class()
if self.view.lookup_sep == ":":
raise AttributeError("The %(cls)s.lookup_sep attribute conflicts with the HaystackFacetFilter "
"query parameter parser. Please choose another `lookup_sep` attribute "
"for %(cls)s." % {"cls": self.view.__class__.__name__})
fields = facet_serializer_cls.Meta.fields
exclude = facet_serializer_cls.Meta.exclude
field_options = facet_serializer_cls.Meta.field_options
for field, options in filters.items():
if field not in fields or field in exclude:
continue
field_options = merge_dict(field_options, {field: self.parse_field_options(self.view.lookup_sep, *options)})
valid_gap = ("year", "month", "day", "hour", "minute", "second")
for field, options in field_options.items():
if any([k in options for k in ("start_date", "end_date", "gap_by", "gap_amount")]):
if not all(("start_date", "end_date", "gap_by" in options)):
raise ValueError("Date faceting requires at least 'start_date', 'end_date' "
"and 'gap_by' to be set.")
if not options["gap_by"] in valid_gap:
raise ValueError("The 'gap_by' parameter must be one of %s." % ", ".join(valid_gap))
options.setdefault("gap_amount", 1)
date_facets[field] = field_options[field]
else:
field_facets[field] = field_options[field]
return {
"date_facets": date_facets,
"field_facets": field_facets,
"query_facets": query_facets
}
|
python
|
def build_query(self, **filters):
"""
Creates a dict of dictionaries suitable for passing to the SearchQuerySet `facet`,
`date_facet` or `query_facet` method. All key word arguments should be wrapped in a list.
:param view: API View
:param dict[str, list[str]] filters: is an expanded QueryDict or a mapping
of keys to a list of parameters.
"""
field_facets = {}
date_facets = {}
query_facets = {}
facet_serializer_cls = self.view.get_facet_serializer_class()
if self.view.lookup_sep == ":":
raise AttributeError("The %(cls)s.lookup_sep attribute conflicts with the HaystackFacetFilter "
"query parameter parser. Please choose another `lookup_sep` attribute "
"for %(cls)s." % {"cls": self.view.__class__.__name__})
fields = facet_serializer_cls.Meta.fields
exclude = facet_serializer_cls.Meta.exclude
field_options = facet_serializer_cls.Meta.field_options
for field, options in filters.items():
if field not in fields or field in exclude:
continue
field_options = merge_dict(field_options, {field: self.parse_field_options(self.view.lookup_sep, *options)})
valid_gap = ("year", "month", "day", "hour", "minute", "second")
for field, options in field_options.items():
if any([k in options for k in ("start_date", "end_date", "gap_by", "gap_amount")]):
if not all(("start_date", "end_date", "gap_by" in options)):
raise ValueError("Date faceting requires at least 'start_date', 'end_date' "
"and 'gap_by' to be set.")
if not options["gap_by"] in valid_gap:
raise ValueError("The 'gap_by' parameter must be one of %s." % ", ".join(valid_gap))
options.setdefault("gap_amount", 1)
date_facets[field] = field_options[field]
else:
field_facets[field] = field_options[field]
return {
"date_facets": date_facets,
"field_facets": field_facets,
"query_facets": query_facets
}
|
[
"def",
"build_query",
"(",
"self",
",",
"*",
"*",
"filters",
")",
":",
"field_facets",
"=",
"{",
"}",
"date_facets",
"=",
"{",
"}",
"query_facets",
"=",
"{",
"}",
"facet_serializer_cls",
"=",
"self",
".",
"view",
".",
"get_facet_serializer_class",
"(",
")",
"if",
"self",
".",
"view",
".",
"lookup_sep",
"==",
"\":\"",
":",
"raise",
"AttributeError",
"(",
"\"The %(cls)s.lookup_sep attribute conflicts with the HaystackFacetFilter \"",
"\"query parameter parser. Please choose another `lookup_sep` attribute \"",
"\"for %(cls)s.\"",
"%",
"{",
"\"cls\"",
":",
"self",
".",
"view",
".",
"__class__",
".",
"__name__",
"}",
")",
"fields",
"=",
"facet_serializer_cls",
".",
"Meta",
".",
"fields",
"exclude",
"=",
"facet_serializer_cls",
".",
"Meta",
".",
"exclude",
"field_options",
"=",
"facet_serializer_cls",
".",
"Meta",
".",
"field_options",
"for",
"field",
",",
"options",
"in",
"filters",
".",
"items",
"(",
")",
":",
"if",
"field",
"not",
"in",
"fields",
"or",
"field",
"in",
"exclude",
":",
"continue",
"field_options",
"=",
"merge_dict",
"(",
"field_options",
",",
"{",
"field",
":",
"self",
".",
"parse_field_options",
"(",
"self",
".",
"view",
".",
"lookup_sep",
",",
"*",
"options",
")",
"}",
")",
"valid_gap",
"=",
"(",
"\"year\"",
",",
"\"month\"",
",",
"\"day\"",
",",
"\"hour\"",
",",
"\"minute\"",
",",
"\"second\"",
")",
"for",
"field",
",",
"options",
"in",
"field_options",
".",
"items",
"(",
")",
":",
"if",
"any",
"(",
"[",
"k",
"in",
"options",
"for",
"k",
"in",
"(",
"\"start_date\"",
",",
"\"end_date\"",
",",
"\"gap_by\"",
",",
"\"gap_amount\"",
")",
"]",
")",
":",
"if",
"not",
"all",
"(",
"(",
"\"start_date\"",
",",
"\"end_date\"",
",",
"\"gap_by\"",
"in",
"options",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Date faceting requires at least 'start_date', 'end_date' \"",
"\"and 'gap_by' to be set.\"",
")",
"if",
"not",
"options",
"[",
"\"gap_by\"",
"]",
"in",
"valid_gap",
":",
"raise",
"ValueError",
"(",
"\"The 'gap_by' parameter must be one of %s.\"",
"%",
"\", \"",
".",
"join",
"(",
"valid_gap",
")",
")",
"options",
".",
"setdefault",
"(",
"\"gap_amount\"",
",",
"1",
")",
"date_facets",
"[",
"field",
"]",
"=",
"field_options",
"[",
"field",
"]",
"else",
":",
"field_facets",
"[",
"field",
"]",
"=",
"field_options",
"[",
"field",
"]",
"return",
"{",
"\"date_facets\"",
":",
"date_facets",
",",
"\"field_facets\"",
":",
"field_facets",
",",
"\"query_facets\"",
":",
"query_facets",
"}"
] |
Creates a dict of dictionaries suitable for passing to the SearchQuerySet `facet`,
`date_facet` or `query_facet` method. All key word arguments should be wrapped in a list.
:param view: API View
:param dict[str, list[str]] filters: is an expanded QueryDict or a mapping
of keys to a list of parameters.
|
[
"Creates",
"a",
"dict",
"of",
"dictionaries",
"suitable",
"for",
"passing",
"to",
"the",
"SearchQuerySet",
"facet",
"date_facet",
"or",
"query_facet",
"method",
".",
"All",
"key",
"word",
"arguments",
"should",
"be",
"wrapped",
"in",
"a",
"list",
"."
] |
ceabd0f6318f129758341ab08292a20205d6f4cd
|
https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/query.py#L159-L210
|
9,998
|
inonit/drf-haystack
|
drf_haystack/query.py
|
FacetQueryBuilder.parse_field_options
|
def parse_field_options(self, *options):
"""
Parse the field options query string and return it as a dictionary.
"""
defaults = {}
for option in options:
if isinstance(option, six.text_type):
tokens = [token.strip() for token in option.split(self.view.lookup_sep)]
for token in tokens:
if not len(token.split(":")) == 2:
warnings.warn("The %s token is not properly formatted. Tokens need to be "
"formatted as 'token:value' pairs." % token)
continue
param, value = token.split(":", 1)
if any([k == param for k in ("start_date", "end_date", "gap_amount")]):
if param in ("start_date", "end_date"):
value = parser.parse(value)
if param == "gap_amount":
value = int(value)
defaults[param] = value
return defaults
|
python
|
def parse_field_options(self, *options):
"""
Parse the field options query string and return it as a dictionary.
"""
defaults = {}
for option in options:
if isinstance(option, six.text_type):
tokens = [token.strip() for token in option.split(self.view.lookup_sep)]
for token in tokens:
if not len(token.split(":")) == 2:
warnings.warn("The %s token is not properly formatted. Tokens need to be "
"formatted as 'token:value' pairs." % token)
continue
param, value = token.split(":", 1)
if any([k == param for k in ("start_date", "end_date", "gap_amount")]):
if param in ("start_date", "end_date"):
value = parser.parse(value)
if param == "gap_amount":
value = int(value)
defaults[param] = value
return defaults
|
[
"def",
"parse_field_options",
"(",
"self",
",",
"*",
"options",
")",
":",
"defaults",
"=",
"{",
"}",
"for",
"option",
"in",
"options",
":",
"if",
"isinstance",
"(",
"option",
",",
"six",
".",
"text_type",
")",
":",
"tokens",
"=",
"[",
"token",
".",
"strip",
"(",
")",
"for",
"token",
"in",
"option",
".",
"split",
"(",
"self",
".",
"view",
".",
"lookup_sep",
")",
"]",
"for",
"token",
"in",
"tokens",
":",
"if",
"not",
"len",
"(",
"token",
".",
"split",
"(",
"\":\"",
")",
")",
"==",
"2",
":",
"warnings",
".",
"warn",
"(",
"\"The %s token is not properly formatted. Tokens need to be \"",
"\"formatted as 'token:value' pairs.\"",
"%",
"token",
")",
"continue",
"param",
",",
"value",
"=",
"token",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"if",
"any",
"(",
"[",
"k",
"==",
"param",
"for",
"k",
"in",
"(",
"\"start_date\"",
",",
"\"end_date\"",
",",
"\"gap_amount\"",
")",
"]",
")",
":",
"if",
"param",
"in",
"(",
"\"start_date\"",
",",
"\"end_date\"",
")",
":",
"value",
"=",
"parser",
".",
"parse",
"(",
"value",
")",
"if",
"param",
"==",
"\"gap_amount\"",
":",
"value",
"=",
"int",
"(",
"value",
")",
"defaults",
"[",
"param",
"]",
"=",
"value",
"return",
"defaults"
] |
Parse the field options query string and return it as a dictionary.
|
[
"Parse",
"the",
"field",
"options",
"query",
"string",
"and",
"return",
"it",
"as",
"a",
"dictionary",
"."
] |
ceabd0f6318f129758341ab08292a20205d6f4cd
|
https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/query.py#L212-L239
|
9,999
|
inonit/drf-haystack
|
drf_haystack/query.py
|
SpatialQueryBuilder.build_query
|
def build_query(self, **filters):
"""
Build queries for geo spatial filtering.
Expected query parameters are:
- a `unit=value` parameter where the unit is a valid UNIT in the
`django.contrib.gis.measure.Distance` class.
- `from` which must be a comma separated latitude and longitude.
Example query:
/api/v1/search/?km=10&from=59.744076,10.152045
Will perform a `dwithin` query within 10 km from the point
with latitude 59.744076 and longitude 10.152045.
"""
applicable_filters = None
filters = dict((k, filters[k]) for k in chain(self.D.UNITS.keys(),
[constants.DRF_HAYSTACK_SPATIAL_QUERY_PARAM]) if k in filters)
distance = dict((k, v) for k, v in filters.items() if k in self.D.UNITS.keys())
try:
latitude, longitude = map(float, self.tokenize(filters[constants.DRF_HAYSTACK_SPATIAL_QUERY_PARAM],
self.view.lookup_sep))
point = self.Point(longitude, latitude, srid=constants.GEO_SRID)
except ValueError:
raise ValueError("Cannot convert `from=latitude,longitude` query parameter to "
"float values. Make sure to provide numerical values only!")
except KeyError:
# If the user has not provided any `from` query string parameter,
# just return.
pass
else:
for unit in distance.keys():
if not len(distance[unit]) == 1:
raise ValueError("Each unit must have exactly one value.")
distance[unit] = float(distance[unit][0])
if point and distance:
applicable_filters = {
"dwithin": {
"field": self.backend.point_field,
"point": point,
"distance": self.D(**distance)
},
"distance": {
"field": self.backend.point_field,
"point": point
}
}
return applicable_filters
|
python
|
def build_query(self, **filters):
"""
Build queries for geo spatial filtering.
Expected query parameters are:
- a `unit=value` parameter where the unit is a valid UNIT in the
`django.contrib.gis.measure.Distance` class.
- `from` which must be a comma separated latitude and longitude.
Example query:
/api/v1/search/?km=10&from=59.744076,10.152045
Will perform a `dwithin` query within 10 km from the point
with latitude 59.744076 and longitude 10.152045.
"""
applicable_filters = None
filters = dict((k, filters[k]) for k in chain(self.D.UNITS.keys(),
[constants.DRF_HAYSTACK_SPATIAL_QUERY_PARAM]) if k in filters)
distance = dict((k, v) for k, v in filters.items() if k in self.D.UNITS.keys())
try:
latitude, longitude = map(float, self.tokenize(filters[constants.DRF_HAYSTACK_SPATIAL_QUERY_PARAM],
self.view.lookup_sep))
point = self.Point(longitude, latitude, srid=constants.GEO_SRID)
except ValueError:
raise ValueError("Cannot convert `from=latitude,longitude` query parameter to "
"float values. Make sure to provide numerical values only!")
except KeyError:
# If the user has not provided any `from` query string parameter,
# just return.
pass
else:
for unit in distance.keys():
if not len(distance[unit]) == 1:
raise ValueError("Each unit must have exactly one value.")
distance[unit] = float(distance[unit][0])
if point and distance:
applicable_filters = {
"dwithin": {
"field": self.backend.point_field,
"point": point,
"distance": self.D(**distance)
},
"distance": {
"field": self.backend.point_field,
"point": point
}
}
return applicable_filters
|
[
"def",
"build_query",
"(",
"self",
",",
"*",
"*",
"filters",
")",
":",
"applicable_filters",
"=",
"None",
"filters",
"=",
"dict",
"(",
"(",
"k",
",",
"filters",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"chain",
"(",
"self",
".",
"D",
".",
"UNITS",
".",
"keys",
"(",
")",
",",
"[",
"constants",
".",
"DRF_HAYSTACK_SPATIAL_QUERY_PARAM",
"]",
")",
"if",
"k",
"in",
"filters",
")",
"distance",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"filters",
".",
"items",
"(",
")",
"if",
"k",
"in",
"self",
".",
"D",
".",
"UNITS",
".",
"keys",
"(",
")",
")",
"try",
":",
"latitude",
",",
"longitude",
"=",
"map",
"(",
"float",
",",
"self",
".",
"tokenize",
"(",
"filters",
"[",
"constants",
".",
"DRF_HAYSTACK_SPATIAL_QUERY_PARAM",
"]",
",",
"self",
".",
"view",
".",
"lookup_sep",
")",
")",
"point",
"=",
"self",
".",
"Point",
"(",
"longitude",
",",
"latitude",
",",
"srid",
"=",
"constants",
".",
"GEO_SRID",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"Cannot convert `from=latitude,longitude` query parameter to \"",
"\"float values. Make sure to provide numerical values only!\"",
")",
"except",
"KeyError",
":",
"# If the user has not provided any `from` query string parameter,",
"# just return.",
"pass",
"else",
":",
"for",
"unit",
"in",
"distance",
".",
"keys",
"(",
")",
":",
"if",
"not",
"len",
"(",
"distance",
"[",
"unit",
"]",
")",
"==",
"1",
":",
"raise",
"ValueError",
"(",
"\"Each unit must have exactly one value.\"",
")",
"distance",
"[",
"unit",
"]",
"=",
"float",
"(",
"distance",
"[",
"unit",
"]",
"[",
"0",
"]",
")",
"if",
"point",
"and",
"distance",
":",
"applicable_filters",
"=",
"{",
"\"dwithin\"",
":",
"{",
"\"field\"",
":",
"self",
".",
"backend",
".",
"point_field",
",",
"\"point\"",
":",
"point",
",",
"\"distance\"",
":",
"self",
".",
"D",
"(",
"*",
"*",
"distance",
")",
"}",
",",
"\"distance\"",
":",
"{",
"\"field\"",
":",
"self",
".",
"backend",
".",
"point_field",
",",
"\"point\"",
":",
"point",
"}",
"}",
"return",
"applicable_filters"
] |
Build queries for geo spatial filtering.
Expected query parameters are:
- a `unit=value` parameter where the unit is a valid UNIT in the
`django.contrib.gis.measure.Distance` class.
- `from` which must be a comma separated latitude and longitude.
Example query:
/api/v1/search/?km=10&from=59.744076,10.152045
Will perform a `dwithin` query within 10 km from the point
with latitude 59.744076 and longitude 10.152045.
|
[
"Build",
"queries",
"for",
"geo",
"spatial",
"filtering",
"."
] |
ceabd0f6318f129758341ab08292a20205d6f4cd
|
https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/query.py#L266-L318
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.