gpg: pydocstyle fixes

nistp521
Roman Zeyde 9 years ago
parent a114242243
commit d7913a84d5

@ -0,0 +1,9 @@
"""
TREZOR support for ECDSA GPG signatures.
See these links for more details:
- https://www.gnupg.org/faq/whats-new-in-2.1.html
- https://tools.ietf.org/html/rfc4880
- https://tools.ietf.org/html/rfc6637
- https://tools.ietf.org/html/draft-irtf-cfrg-eddsa-05
"""

@ -1,4 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
"""Check GPG v2 signature for a given public key."""
import argparse import argparse
import base64 import base64
import io import io
@ -11,6 +12,7 @@ log = logging.getLogger(__name__)
def original_data(filename): def original_data(filename):
"""Locate and load original file data, whose signature is provided."""
parts = filename.rsplit('.', 1) parts = filename.rsplit('.', 1)
if len(parts) == 2 and parts[1] in ('sig', 'asc'): if len(parts) == 2 and parts[1] in ('sig', 'asc'):
log.debug('loading file %s', parts[0]) log.debug('loading file %s', parts[0])
@ -21,6 +23,7 @@ def verify(pubkey, sig_file):
d = open(sig_file, 'rb') d = open(sig_file, 'rb')
if d.name.endswith('.asc'): if d.name.endswith('.asc'):
lines = d.readlines()[3:-1] lines = d.readlines()[3:-1]
"""Verify correctness of public key and signature."""
data = base64.b64decode(''.join(lines)) data = base64.b64decode(''.join(lines))
payload, checksum = data[:-3], data[-3:] payload, checksum = data[:-3], data[-3:]
assert util.crc24(payload) == checksum assert util.crc24(payload) == checksum
@ -33,6 +36,7 @@ def verify(pubkey, sig_file):
def main(): def main():
"""Main function."""
logging.basicConfig(level=logging.DEBUG, logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)-10s %(message)s') format='%(asctime)s %(levelname)-10s %(message)s')
p = argparse.ArgumentParser() p = argparse.ArgumentParser()

@ -1,3 +1,4 @@
"""Decoders for GPG v2 data structures."""
import binascii import binascii
import contextlib import contextlib
import hashlib import hashlib
@ -14,31 +15,39 @@ log = logging.getLogger(__name__)
def bit(value, i): def bit(value, i):
"""Extract the i-th bit out of value."""
return 1 if value & (1 << i) else 0 return 1 if value & (1 << i) else 0
def low_bits(value, n): def low_bits(value, n):
"""Extract the lowest n bits out of value."""
return value & ((1 << n) - 1) return value & ((1 << n) - 1)
def readfmt(stream, fmt): def readfmt(stream, fmt):
"""Read and unpack an object from stream, using a struct format string."""
size = struct.calcsize(fmt) size = struct.calcsize(fmt)
blob = stream.read(size) blob = stream.read(size)
return struct.unpack(fmt, blob) return struct.unpack(fmt, blob)
class Reader(object): class Reader(object):
"""Read basic type objects out of given stream."""
def __init__(self, stream): def __init__(self, stream):
"""Create a non-capturing reader."""
self.s = stream self.s = stream
self._captured = None self._captured = None
def readfmt(self, fmt): def readfmt(self, fmt):
"""Read a specified object, using a struct format string."""
size = struct.calcsize(fmt) size = struct.calcsize(fmt)
blob = self.read(size) blob = self.read(size)
obj, = struct.unpack(fmt, blob) obj, = struct.unpack(fmt, blob)
return obj return obj
def read(self, size=None): def read(self, size=None):
"""Read `size` bytes from stream."""
blob = self.s.read(size) blob = self.s.read(size)
if size is not None and len(blob) < size: if size is not None and len(blob) < size:
raise EOFError raise EOFError
@ -48,6 +57,7 @@ class Reader(object):
@contextlib.contextmanager @contextlib.contextmanager
def capture(self, stream): def capture(self, stream):
"""Capture all data read during this context."""
self._captured = stream self._captured = stream
try: try:
yield yield
@ -58,6 +68,7 @@ length_types = {0: '>B', 1: '>H', 2: '>L'}
def parse_subpackets(s): def parse_subpackets(s):
"""See https://tools.ietf.org/html/rfc4880#section-5.2.3.1 for details."""
subpackets = [] subpackets = []
total_size = s.readfmt('>H') total_size = s.readfmt('>H')
data = s.read(total_size) data = s.read(total_size)
@ -75,12 +86,18 @@ def parse_subpackets(s):
def parse_mpi(s): def parse_mpi(s):
"""See https://tools.ietf.org/html/rfc4880#section-3.2 for details."""
bits = s.readfmt('>H') bits = s.readfmt('>H')
blob = bytearray(s.read(int((bits + 7) // 8))) blob = bytearray(s.read(int((bits + 7) // 8)))
return sum(v << (8 * i) for i, v in enumerate(reversed(blob))) return sum(v << (8 * i) for i, v in enumerate(reversed(blob)))
def split_bits(value, *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 = [] result = []
for b in reversed(bits): for b in reversed(bits):
mask = (1 << b) - 1 mask = (1 << b) - 1
@ -125,11 +142,13 @@ SUPPORTED_CURVES = {
class Parser(object): class Parser(object):
"""Parse GPG packets from a given stream."""
def __init__(self, stream, to_hash=None): def __init__(self, stream, to_hash=None):
"""Create an empty parser."""
self.stream = stream self.stream = stream
self.packet_types = { self.packet_types = {
2: self.signature, 2: self.signature,
4: self.onepass,
6: self.pubkey, 6: self.pubkey,
11: self.literal, 11: self.literal,
13: self.user_id, 13: self.user_id,
@ -139,21 +158,11 @@ class Parser(object):
self.to_hash.write(to_hash) self.to_hash.write(to_hash)
def __iter__(self): def __iter__(self):
"""Support iterative parsing of available GPG packets."""
return self return self
def onepass(self, stream):
# pylint: disable=no-self-use
p = {'type': 'onepass'}
p['version'] = stream.readfmt('B')
p['sig_type'] = stream.readfmt('B')
p['hash_alg'] = stream.readfmt('B')
p['pubkey_alg'] = stream.readfmt('B')
p['key_id'] = stream.readfmt('8s')
p['nested'] = stream.readfmt('B')
assert not stream.read()
return p
def literal(self, stream): def literal(self, stream):
"""See https://tools.ietf.org/html/rfc4880#section-5.9 for details."""
p = {'type': 'literal'} p = {'type': 'literal'}
p['format'] = stream.readfmt('c') p['format'] = stream.readfmt('c')
filename_len = stream.readfmt('B') filename_len = stream.readfmt('B')
@ -164,6 +173,7 @@ class Parser(object):
return p return p
def signature(self, stream): def signature(self, stream):
"""See https://tools.ietf.org/html/rfc4880#section-5.2 for details."""
p = {'type': 'signature'} p = {'type': 'signature'}
to_hash = io.BytesIO() to_hash = io.BytesIO()
@ -195,6 +205,7 @@ class Parser(object):
return p return p
def pubkey(self, stream): def pubkey(self, stream):
"""See https://tools.ietf.org/html/rfc4880#section-5.5 for details."""
p = {'type': 'pubkey'} p = {'type': 'pubkey'}
packet = io.BytesIO() packet = io.BytesIO()
with stream.capture(packet): with stream.capture(packet):
@ -224,14 +235,15 @@ class Parser(object):
return p return p
def user_id(self, stream): def user_id(self, stream):
"""See https://tools.ietf.org/html/rfc4880#section-5.11 for details."""
value = stream.read() value = stream.read()
self.to_hash.write(b'\xb4' + struct.pack('>L', len(value))) self.to_hash.write(b'\xb4' + struct.pack('>L', len(value)))
self.to_hash.write(value) self.to_hash.write(value)
return {'type': 'user_id', 'value': value} return {'type': 'user_id', 'value': value}
def __next__(self): def __next__(self):
"""See https://tools.ietf.org/html/rfc4880#section-4.2 for details."""
try: try:
# https://tools.ietf.org/html/rfc4880#section-4.2
value = self.stream.readfmt('B') value = self.stream.readfmt('B')
except EOFError: except EOFError:
raise StopIteration raise StopIteration
@ -252,7 +264,7 @@ class Parser(object):
if packet_type: if packet_type:
p = packet_type(Reader(io.BytesIO(packet_data))) p = packet_type(Reader(io.BytesIO(packet_data)))
else: else:
p = {'type': 'UNKNOWN'} raise ValueError('Unknown packet type: {}'.format(packet_type))
p['tag'] = tag p['tag'] = tag
log.debug('packet "%s": %s', p['type'], p) log.debug('packet "%s": %s', p['type'], p)
return p return p
@ -261,6 +273,7 @@ class Parser(object):
def load_public_key(stream): def load_public_key(stream):
"""Parse and validate GPG public key from an input stream."""
parser = Parser(Reader(stream)) parser = Parser(Reader(stream))
pubkey, userid, signature = list(parser) pubkey, userid, signature = list(parser)
log.debug('loaded public key "%s"', userid['value']) log.debug('loaded public key "%s"', userid['value'])
@ -270,6 +283,7 @@ def load_public_key(stream):
def verify_digest(pubkey, digest, signature, label): def verify_digest(pubkey, digest, signature, label):
"""Verify a digest signature from a specified public key."""
verifier = pubkey['verifier'] verifier = pubkey['verifier']
try: try:
verifier(signature, digest) verifier(signature, digest)

@ -1,4 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
"""A simple wrapper for Git commit/tag GPG signing."""
import logging import logging
import subprocess as sp import subprocess as sp
import sys import sys
@ -9,6 +10,7 @@ log = logging.getLogger(__name__)
def main(): def main():
"""Main function."""
logging.basicConfig(level=logging.INFO, logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)-10s %(message)s') format='%(asctime)s %(levelname)-10s %(message)s')

@ -1,4 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
"""Create GPG ECDSA signatures and public keys using TREZOR device."""
import argparse import argparse
import base64 import base64
import binascii import binascii
@ -16,10 +17,12 @@ log = logging.getLogger(__name__)
def prefix_len(fmt, blob): def prefix_len(fmt, blob):
"""Prefix `blob` with its size, serialized using `fmt` format."""
return struct.pack(fmt, len(blob)) + blob return struct.pack(fmt, len(blob)) + blob
def packet(tag, blob): def packet(tag, blob):
"""Create small GPG packet."""
assert len(blob) < 256 assert len(blob) < 256
length_type = 0 # : 1 byte for length length_type = 0 # : 1 byte for length
leading_byte = 0x80 | (tag << 2) | (length_type) leading_byte = 0x80 | (tag << 2) | (length_type)
@ -27,28 +30,34 @@ def packet(tag, blob):
def subpacket(subpacket_type, fmt, *values): def subpacket(subpacket_type, fmt, *values):
"""Create GPG subpacket."""
blob = struct.pack(fmt, *values) if values else fmt blob = struct.pack(fmt, *values) if values else fmt
return struct.pack('>B', subpacket_type) + blob return struct.pack('>B', subpacket_type) + blob
def subpacket_long(subpacket_type, value): def subpacket_long(subpacket_type, value):
"""Create GPG subpacket with 32-bit unsigned integer."""
return subpacket(subpacket_type, '>L', value) return subpacket(subpacket_type, '>L', value)
def subpacket_time(value): def subpacket_time(value):
"""Create GPG subpacket with time in seconds (since Epoch)."""
return subpacket_long(2, value) return subpacket_long(2, value)
def subpacket_byte(subpacket_type, value): def subpacket_byte(subpacket_type, value):
"""Create GPG subpacket with 8-bit unsigned integer."""
return subpacket(subpacket_type, '>B', value) return subpacket(subpacket_type, '>B', value)
def subpackets(*items): def subpackets(*items):
"""Serialize several GPG subpackets."""
prefixed = [prefix_len('>B', item) for item in items] prefixed = [prefix_len('>B', item) for item in items]
return prefix_len('>H', b''.join(prefixed)) return prefix_len('>H', b''.join(prefixed))
def mpi(value): def mpi(value):
"""Serialize multipresicion integer using GPG format."""
bits = value.bit_length() bits = value.bit_length()
data_size = (bits + 7) // 8 data_size = (bits + 7) // 8
data_bytes = [0] * data_size data_bytes = [0] * data_size
@ -61,10 +70,12 @@ def mpi(value):
def time_format(t): def time_format(t):
"""Utility for consistent time formatting."""
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t)) return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t))
def hexlify(blob): def hexlify(blob):
"""Utility for consistent hexadecimal formatting."""
return binascii.hexlify(blob).decode('ascii').upper() return binascii.hexlify(blob).decode('ascii').upper()
@ -94,15 +105,17 @@ SUPPORTED_CURVES = {
} }
def find_curve_by_algo_id(algo_id): def _find_curve_by_algo_id(algo_id):
curve_name, = [name for name, info in SUPPORTED_CURVES.items() curve_name, = [name for name, info in SUPPORTED_CURVES.items()
if info['algo_id'] == algo_id] if info['algo_id'] == algo_id]
return curve_name return curve_name
class Signer(object): class Signer(object):
"""Performs GPG operations with the TREZOR."""
def __init__(self, user_id, created, curve_name): def __init__(self, user_id, created, curve_name):
"""Construct and loads a public key from the device."""
self.user_id = user_id self.user_id = user_id
assert curve_name in formats.SUPPORTED_CURVES assert curve_name in formats.SUPPORTED_CURVES
self.curve_name = curve_name self.curve_name = curve_name
@ -126,9 +139,15 @@ class Signer(object):
@classmethod @classmethod
def from_public_key(cls, pubkey, user_id): def from_public_key(cls, pubkey, user_id):
"""
Create from an existing GPG public key.
`pubkey` should be loaded via `load_from_gpg(user_id)`
from the local GPG keyring.
"""
s = Signer(user_id=user_id, s = Signer(user_id=user_id,
created=pubkey['created'], created=pubkey['created'],
curve_name=find_curve_by_algo_id(pubkey['algo'])) curve_name=_find_curve_by_algo_id(pubkey['algo']))
assert s.key_id() == pubkey['key_id'] assert s.key_id() == pubkey['key_id']
return s return s
@ -149,16 +168,20 @@ class Signer(object):
return hashlib.sha1(self._pubkey_data_to_hash()).digest() return hashlib.sha1(self._pubkey_data_to_hash()).digest()
def key_id(self): def key_id(self):
"""Short (8 byte) GPG key ID."""
return self._fingerprint()[-8:] return self._fingerprint()[-8:]
def hex_short_key_id(self): def hex_short_key_id(self):
"""Short (8 hexadecimal digits) GPG key ID."""
return hexlify(self.key_id()[-4:]) return hexlify(self.key_id()[-4:])
def close(self): def close(self):
"""Close connection and turn off the screen of the device."""
self.client_wrapper.connection.clear_session() self.client_wrapper.connection.clear_session()
self.client_wrapper.connection.close() self.client_wrapper.connection.close()
def export(self): def export(self):
"""Export GPG public key, ready for "gpg2 --import"."""
pubkey_packet = packet(tag=6, blob=self._pubkey_data()) pubkey_packet = packet(tag=6, blob=self._pubkey_data())
user_id_packet = packet(tag=13, blob=self.user_id) user_id_packet = packet(tag=13, blob=self.user_id)
@ -180,6 +203,7 @@ class Signer(object):
return pubkey_packet + user_id_packet + sign_packet return pubkey_packet + user_id_packet + sign_packet
def sign(self, msg, sign_time=None): def sign(self, msg, sign_time=None):
"""Sign GPG message at specified time."""
if sign_time is None: if sign_time is None:
sign_time = int(time.time()) sign_time = int(time.time())
@ -223,7 +247,7 @@ class Signer(object):
sig) # actual ECDSA signature sig) # actual ECDSA signature
def split_lines(body, size): def _split_lines(body, size):
lines = [] lines = []
for i in range(0, len(body), size): for i in range(0, len(body), size):
lines.append(body[i:i+size] + '\n') lines.append(body[i:i+size] + '\n')
@ -231,14 +255,16 @@ def split_lines(body, size):
def armor(blob, type_str): def armor(blob, type_str):
"""See https://tools.ietf.org/html/rfc4880#section-6 for details."""
head = '-----BEGIN PGP {}-----\nVersion: GnuPG v2\n\n'.format(type_str) head = '-----BEGIN PGP {}-----\nVersion: GnuPG v2\n\n'.format(type_str)
body = base64.b64encode(blob) body = base64.b64encode(blob)
checksum = base64.b64encode(util.crc24(blob)) checksum = base64.b64encode(util.crc24(blob))
tail = '-----END PGP {}-----\n'.format(type_str) tail = '-----END PGP {}-----\n'.format(type_str)
return head + split_lines(body, 64) + '=' + checksum + '\n' + tail return head + _split_lines(body, 64) + '=' + checksum + '\n' + tail
def load_from_gpg(user_id): def load_from_gpg(user_id):
"""Load existing GPG public key for `user_id` from local keyring."""
pubkey_bytes = subprocess.check_output(['gpg2', '--export', user_id]) pubkey_bytes = subprocess.check_output(['gpg2', '--export', user_id])
if pubkey_bytes: if pubkey_bytes:
return decode.load_public_key(io.BytesIO(pubkey_bytes)) return decode.load_public_key(io.BytesIO(pubkey_bytes))
@ -248,6 +274,7 @@ def load_from_gpg(user_id):
def main(): def main():
"""Main function."""
p = argparse.ArgumentParser() p = argparse.ArgumentParser()
p.add_argument('user_id') p.add_argument('user_id')
p.add_argument('filename', nargs='?') p.add_argument('filename', nargs='?')

@ -78,6 +78,7 @@ def frame(*msgs):
def crc24(blob): def crc24(blob):
"""See https://tools.ietf.org/html/rfc4880#section-6.1 for details."""
CRC24_INIT = 0x0B704CE CRC24_INIT = 0x0B704CE
CRC24_POLY = 0x1864CFB CRC24_POLY = 0x1864CFB

Loading…
Cancel
Save