2016-04-16 18:21:12 +00:00
|
|
|
#!/usr/bin/env python
|
|
|
|
import argparse
|
|
|
|
import base64
|
|
|
|
import binascii
|
|
|
|
import hashlib
|
2016-04-17 20:03:41 +00:00
|
|
|
import io
|
2016-04-16 18:21:12 +00:00
|
|
|
import logging
|
|
|
|
import struct
|
2016-04-17 20:03:41 +00:00
|
|
|
import subprocess
|
2016-04-16 18:21:12 +00:00
|
|
|
import time
|
|
|
|
|
2016-04-23 19:08:18 +00:00
|
|
|
from . import decode
|
|
|
|
from .. import client, factory, formats
|
|
|
|
from .. import util
|
2016-04-16 18:21:12 +00:00
|
|
|
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
def prefix_len(fmt, blob):
|
|
|
|
return struct.pack(fmt, len(blob)) + blob
|
|
|
|
|
|
|
|
|
|
|
|
def packet(tag, blob):
|
|
|
|
assert len(blob) < 256
|
|
|
|
length_type = 0 # : 1 byte for length
|
|
|
|
leading_byte = 0x80 | (tag << 2) | (length_type)
|
|
|
|
return struct.pack('>B', leading_byte) + prefix_len('>B', blob)
|
|
|
|
|
|
|
|
|
|
|
|
def subpacket(subpacket_type, fmt, *values):
|
|
|
|
blob = struct.pack(fmt, *values) if values else fmt
|
|
|
|
return struct.pack('>B', subpacket_type) + blob
|
|
|
|
|
|
|
|
|
|
|
|
def subpacket_long(subpacket_type, value):
|
|
|
|
return subpacket(subpacket_type, '>L', value)
|
|
|
|
|
|
|
|
|
|
|
|
def subpacket_time(value):
|
|
|
|
return subpacket_long(2, value)
|
|
|
|
|
|
|
|
|
|
|
|
def subpacket_byte(subpacket_type, value):
|
|
|
|
return subpacket(subpacket_type, '>B', value)
|
|
|
|
|
|
|
|
|
|
|
|
def subpackets(*items):
|
|
|
|
prefixed = [prefix_len('>B', item) for item in items]
|
|
|
|
return prefix_len('>H', b''.join(prefixed))
|
|
|
|
|
|
|
|
|
|
|
|
def mpi(value):
|
|
|
|
bits = value.bit_length()
|
|
|
|
data_size = (bits + 7) // 8
|
|
|
|
data_bytes = [0] * data_size
|
|
|
|
for i in range(data_size):
|
|
|
|
data_bytes[i] = value & 0xFF
|
|
|
|
value = value >> 8
|
|
|
|
|
|
|
|
data_bytes.reverse()
|
|
|
|
return struct.pack('>H', bits) + bytearray(data_bytes)
|
|
|
|
|
|
|
|
|
|
|
|
def time_format(t):
|
|
|
|
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t))
|
|
|
|
|
|
|
|
|
|
|
|
def hexlify(blob):
|
|
|
|
return binascii.hexlify(blob).decode('ascii').upper()
|
|
|
|
|
|
|
|
|
2016-04-22 20:37:04 +00:00
|
|
|
def _dump_nist256(vk):
|
|
|
|
return mpi((4 << 512) |
|
|
|
|
(vk.pubkey.point.x() << 256) |
|
|
|
|
(vk.pubkey.point.y()))
|
|
|
|
|
|
|
|
|
|
|
|
def _dump_ed25519(vk):
|
|
|
|
return mpi((0x40 << 256) |
|
2016-04-23 19:08:18 +00:00
|
|
|
util.bytes2num(vk.to_bytes()))
|
2016-04-22 20:37:04 +00:00
|
|
|
|
2016-04-16 18:21:12 +00:00
|
|
|
|
2016-04-22 20:37:04 +00:00
|
|
|
SUPPORTED_CURVES = {
|
2016-04-23 19:08:18 +00:00
|
|
|
formats.CURVE_NIST256: {
|
2016-04-22 20:37:04 +00:00
|
|
|
# https://tools.ietf.org/html/rfc6637#section-11
|
|
|
|
'oid': b'\x2A\x86\x48\xCE\x3D\x03\x01\x07',
|
|
|
|
'algo_id': 19,
|
|
|
|
'dump': _dump_nist256
|
|
|
|
},
|
2016-04-23 19:08:18 +00:00
|
|
|
formats.CURVE_ED25519: {
|
2016-04-22 20:37:04 +00:00
|
|
|
'oid': b'\x2B\x06\x01\x04\x01\xDA\x47\x0F\x01',
|
|
|
|
'algo_id': 22,
|
|
|
|
'dump': _dump_ed25519
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-04-23 19:08:18 +00:00
|
|
|
|
2016-04-22 21:08:45 +00:00
|
|
|
def find_curve_by_algo_id(algo_id):
|
|
|
|
curve_name, = [name for name, info in SUPPORTED_CURVES.items()
|
|
|
|
if info['algo_id'] == algo_id]
|
|
|
|
return curve_name
|
|
|
|
|
2016-04-22 20:37:04 +00:00
|
|
|
|
|
|
|
class Signer(object):
|
2016-04-16 18:21:12 +00:00
|
|
|
|
2016-04-22 20:37:04 +00:00
|
|
|
def __init__(self, user_id, created, curve_name):
|
2016-04-16 18:21:12 +00:00
|
|
|
self.user_id = user_id
|
2016-04-23 19:08:18 +00:00
|
|
|
assert curve_name in formats.SUPPORTED_CURVES
|
2016-04-22 20:37:04 +00:00
|
|
|
self.curve_name = curve_name
|
2016-04-23 19:08:18 +00:00
|
|
|
self.client_wrapper = factory.load()
|
2016-04-16 18:21:12 +00:00
|
|
|
|
|
|
|
self.identity = self.client_wrapper.identity_type()
|
|
|
|
self.identity.proto = 'gpg'
|
|
|
|
self.identity.host = user_id
|
2016-04-18 19:10:00 +00:00
|
|
|
|
2016-04-23 19:08:18 +00:00
|
|
|
addr = client.get_address(self.identity)
|
2016-04-16 18:21:12 +00:00
|
|
|
public_node = self.client_wrapper.connection.get_public_node(
|
2016-04-22 20:37:04 +00:00
|
|
|
n=addr, ecdsa_curve_name=self.curve_name)
|
2016-04-16 18:21:12 +00:00
|
|
|
|
2016-04-23 19:08:18 +00:00
|
|
|
self.verifying_key = formats.decompress_pubkey(
|
2016-04-16 18:21:12 +00:00
|
|
|
pubkey=public_node.node.public_key,
|
2016-04-22 20:37:04 +00:00
|
|
|
curve_name=self.curve_name)
|
2016-04-16 18:21:12 +00:00
|
|
|
|
|
|
|
self.created = int(created)
|
2016-04-23 16:31:23 +00:00
|
|
|
log.info('%s GPG public key %s created at %s', self.curve_name,
|
2016-04-20 18:41:46 +00:00
|
|
|
self.hex_short_key_id(), time_format(self.created))
|
2016-04-18 19:10:00 +00:00
|
|
|
|
|
|
|
def _pubkey_data(self):
|
2016-04-22 20:37:04 +00:00
|
|
|
curve_info = SUPPORTED_CURVES[self.curve_name]
|
2016-04-16 18:21:12 +00:00
|
|
|
header = struct.pack('>BLB',
|
|
|
|
4, # version
|
|
|
|
self.created, # creation
|
2016-04-22 20:37:04 +00:00
|
|
|
curve_info['algo_id'])
|
|
|
|
oid = prefix_len('>B', curve_info['oid'])
|
|
|
|
blob = curve_info['dump'](self.verifying_key)
|
|
|
|
return header + oid + blob
|
2016-04-16 18:21:12 +00:00
|
|
|
|
2016-04-18 19:10:00 +00:00
|
|
|
def _pubkey_data_to_hash(self):
|
|
|
|
return b'\x99' + prefix_len('>H', self._pubkey_data())
|
2016-04-16 18:21:12 +00:00
|
|
|
|
2016-04-18 19:10:00 +00:00
|
|
|
def _fingerprint(self):
|
|
|
|
return hashlib.sha1(self._pubkey_data_to_hash()).digest()
|
|
|
|
|
|
|
|
def key_id(self):
|
|
|
|
return self._fingerprint()[-8:]
|
2016-04-16 18:21:12 +00:00
|
|
|
|
2016-04-20 18:41:46 +00:00
|
|
|
def hex_short_key_id(self):
|
|
|
|
return hexlify(self.key_id()[-4:])
|
|
|
|
|
2016-04-16 18:21:12 +00:00
|
|
|
def close(self):
|
|
|
|
self.client_wrapper.connection.clear_session()
|
|
|
|
self.client_wrapper.connection.close()
|
|
|
|
|
|
|
|
def export(self):
|
2016-04-18 19:10:00 +00:00
|
|
|
pubkey_packet = packet(tag=6, blob=self._pubkey_data())
|
2016-04-16 18:21:12 +00:00
|
|
|
user_id_packet = packet(tag=13, blob=self.user_id)
|
|
|
|
|
|
|
|
user_id_to_hash = user_id_packet[:1] + prefix_len('>L', self.user_id)
|
2016-04-18 19:10:00 +00:00
|
|
|
data_to_sign = self._pubkey_data_to_hash() + user_id_to_hash
|
2016-04-20 18:41:46 +00:00
|
|
|
log.info('signing public key "%s"', self.user_id)
|
2016-04-16 18:21:12 +00:00
|
|
|
hashed_subpackets = [
|
|
|
|
subpacket_time(self.created), # signature creaion time
|
|
|
|
subpacket_byte(0x1B, 1 | 2), # key flags (certify & sign)
|
|
|
|
subpacket_byte(0x15, 8), # preferred hash (SHA256)
|
|
|
|
subpacket_byte(0x16, 0), # preferred compression (none)
|
|
|
|
subpacket_byte(0x17, 0x80)] # key server prefs (no-modify)
|
2016-04-20 18:41:46 +00:00
|
|
|
signature = self._make_signature(visual=self.hex_short_key_id(),
|
2016-04-16 18:21:12 +00:00
|
|
|
data_to_sign=data_to_sign,
|
|
|
|
sig_type=0x13, # user id & public key
|
|
|
|
hashed_subpackets=hashed_subpackets)
|
|
|
|
|
|
|
|
sign_packet = packet(tag=2, blob=signature)
|
|
|
|
return pubkey_packet + user_id_packet + sign_packet
|
|
|
|
|
|
|
|
def sign(self, msg, sign_time=None):
|
|
|
|
if sign_time is None:
|
|
|
|
sign_time = int(time.time())
|
|
|
|
|
2016-04-23 16:31:23 +00:00
|
|
|
log.info('signing %d byte message at %s',
|
|
|
|
len(msg), time_format(sign_time))
|
2016-04-16 18:21:12 +00:00
|
|
|
hashed_subpackets = [subpacket_time(sign_time)]
|
|
|
|
blob = self._make_signature(
|
2016-04-20 18:41:46 +00:00
|
|
|
visual=self.hex_short_key_id(),
|
2016-04-16 18:21:12 +00:00
|
|
|
data_to_sign=msg, hashed_subpackets=hashed_subpackets)
|
|
|
|
return packet(tag=2, blob=blob)
|
|
|
|
|
2016-04-23 19:08:18 +00:00
|
|
|
|
2016-04-16 18:21:12 +00:00
|
|
|
def _make_signature(self, visual, data_to_sign,
|
|
|
|
hashed_subpackets, sig_type=0):
|
2016-04-22 20:37:04 +00:00
|
|
|
curve_info = SUPPORTED_CURVES[self.curve_name]
|
2016-04-16 18:21:12 +00:00
|
|
|
header = struct.pack('>BBBB',
|
|
|
|
4, # version
|
|
|
|
sig_type, # rfc4880 (section-5.2.1)
|
2016-04-22 20:37:04 +00:00
|
|
|
curve_info['algo_id'],
|
2016-04-16 18:21:12 +00:00
|
|
|
8) # hash_alg (SHA256)
|
|
|
|
hashed = subpackets(*hashed_subpackets)
|
|
|
|
unhashed = subpackets(
|
2016-04-18 19:10:00 +00:00
|
|
|
subpacket(16, self.key_id()) # issuer key id
|
2016-04-16 18:21:12 +00:00
|
|
|
)
|
|
|
|
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()
|
|
|
|
|
|
|
|
result = self.client_wrapper.connection.sign_identity(
|
|
|
|
identity=self.identity,
|
2016-04-18 18:55:23 +00:00
|
|
|
challenge_hidden=digest,
|
2016-04-16 18:21:12 +00:00
|
|
|
challenge_visual=visual,
|
2016-04-22 20:37:04 +00:00
|
|
|
ecdsa_curve_name=self.curve_name)
|
2016-04-16 18:21:12 +00:00
|
|
|
assert result.signature[:1] == b'\x00'
|
|
|
|
sig = result.signature[1:]
|
2016-04-23 19:08:18 +00:00
|
|
|
sig = [util.bytes2num(sig[:32]),
|
|
|
|
util.bytes2num(sig[32:])]
|
2016-04-16 18:21:12 +00:00
|
|
|
|
|
|
|
hash_prefix = digest[:2] # used for decoder's sanity check
|
|
|
|
signature = mpi(sig[0]) + mpi(sig[1]) # actual ECDSA signature
|
|
|
|
return header + hashed + unhashed + hash_prefix + signature
|
2016-04-22 20:37:04 +00:00
|
|
|
# TODO: add verification
|
2016-04-16 18:21:12 +00:00
|
|
|
|
|
|
|
|
2016-04-17 19:40:02 +00:00
|
|
|
def split_lines(body, size):
|
|
|
|
lines = []
|
|
|
|
for i in range(0, len(body), size):
|
|
|
|
lines.append(body[i:i+size] + '\n')
|
|
|
|
return ''.join(lines)
|
|
|
|
|
|
|
|
|
|
|
|
def armor(blob, type_str):
|
|
|
|
head = '-----BEGIN PGP {}-----\nVersion: GnuPG v2\n\n'.format(type_str)
|
|
|
|
body = base64.b64encode(blob)
|
|
|
|
checksum = base64.b64encode(util.crc24(blob))
|
|
|
|
tail = '-----END PGP {}-----\n'.format(type_str)
|
|
|
|
return head + split_lines(body, 64) + '=' + checksum + '\n' + tail
|
|
|
|
|
|
|
|
|
2016-04-17 20:03:41 +00:00
|
|
|
def load_from_gpg(user_id):
|
2016-04-23 16:31:23 +00:00
|
|
|
log.info('loading public key %r from local GPG keyring', user_id)
|
2016-04-17 20:03:41 +00:00
|
|
|
pubkey_bytes = subprocess.check_output(['gpg2', '--export', user_id])
|
|
|
|
pubkey = decode.load_public_key(io.BytesIO(pubkey_bytes))
|
2016-04-22 21:08:45 +00:00
|
|
|
s = Signer(user_id=user_id,
|
|
|
|
created=pubkey['created'],
|
|
|
|
curve_name=find_curve_by_algo_id(pubkey['algo']))
|
|
|
|
assert s.key_id() == pubkey['key_id']
|
|
|
|
return s
|
2016-04-17 20:03:41 +00:00
|
|
|
|
|
|
|
|
2016-04-16 18:21:12 +00:00
|
|
|
def main():
|
|
|
|
p = argparse.ArgumentParser()
|
|
|
|
p.add_argument('user_id')
|
2016-04-22 18:37:23 +00:00
|
|
|
p.add_argument('filename', nargs='?')
|
2016-04-16 18:21:12 +00:00
|
|
|
p.add_argument('-t', '--time', type=int, default=int(time.time()))
|
|
|
|
p.add_argument('-a', '--armor', action='store_true', default=False)
|
|
|
|
p.add_argument('-v', '--verbose', action='store_true', default=False)
|
2016-04-22 20:37:04 +00:00
|
|
|
p.add_argument('-e', '--ecdsa-curve', default='nist256p1')
|
2016-04-16 18:21:12 +00:00
|
|
|
|
|
|
|
args = p.parse_args()
|
|
|
|
logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO,
|
|
|
|
format='%(asctime)s %(levelname)-10s %(message)s')
|
2016-04-17 20:03:41 +00:00
|
|
|
user_id = args.user_id.encode('ascii')
|
2016-04-18 18:55:23 +00:00
|
|
|
if not args.filename:
|
2016-04-22 20:37:04 +00:00
|
|
|
s = Signer(user_id=user_id, created=args.time,
|
|
|
|
curve_name=args.ecdsa_curve)
|
2016-04-17 19:40:02 +00:00
|
|
|
pubkey = s.export()
|
|
|
|
ext = '.pub'
|
|
|
|
if args.armor:
|
|
|
|
pubkey = armor(pubkey, 'PUBLIC KEY BLOCK')
|
|
|
|
ext = '.asc'
|
2016-04-22 20:37:04 +00:00
|
|
|
filename = s.hex_short_key_id() + ext
|
|
|
|
open(filename, 'wb').write(pubkey)
|
|
|
|
log.info('import to local keyring using "gpg2 --import %s"', filename)
|
2016-04-18 18:55:23 +00:00
|
|
|
else:
|
2016-04-22 21:08:45 +00:00
|
|
|
s = load_from_gpg(user_id)
|
2016-04-16 18:21:12 +00:00
|
|
|
data = open(args.filename, 'rb').read()
|
|
|
|
sig, ext = s.sign(data), '.sig'
|
|
|
|
if args.armor:
|
2016-04-17 20:03:41 +00:00
|
|
|
sig = armor(sig, 'SIGNATURE')
|
|
|
|
ext = '.asc'
|
2016-04-16 18:21:12 +00:00
|
|
|
open(args.filename + ext, 'wb').write(sig)
|
2016-04-17 19:40:02 +00:00
|
|
|
|
2016-04-16 18:21:12 +00:00
|
|
|
s.close()
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|