2019-12-11 04:32:07 -05:00
|
|
|
import copy
|
|
|
|
import io
|
|
|
|
import os
|
|
|
|
import shutil
|
|
|
|
import tempfile
|
|
|
|
##
|
|
|
|
import gpg
|
|
|
|
import gpg.errors
|
|
|
|
|
|
|
|
|
2019-12-17 03:40:08 -05:00
|
|
|
class KeyEditor(object):
|
|
|
|
def __init__(self):
|
|
|
|
self.trusted = False
|
|
|
|
|
|
|
|
def truster(self, kw, arg, *args, **kwargs):
|
|
|
|
if kw == 'GET_LINE':
|
|
|
|
if arg == 'keyedit.prompt':
|
|
|
|
if not self.trusted:
|
|
|
|
return('trust')
|
|
|
|
else:
|
|
|
|
return('save')
|
|
|
|
elif arg == 'edit_ownertrust.value' and not self.trusted:
|
|
|
|
self.trusted = True
|
|
|
|
return('4') # "Full"
|
|
|
|
else:
|
|
|
|
return('save')
|
|
|
|
return(None)
|
|
|
|
|
|
|
|
|
2019-12-11 04:32:07 -05:00
|
|
|
class GPG(object):
|
2019-12-17 03:40:08 -05:00
|
|
|
def __init__(self, homedir = None, primary_key = None, *args, **kwargs):
|
2019-12-11 04:32:07 -05:00
|
|
|
self.homedir = homedir
|
|
|
|
self.primary_key = primary_key
|
|
|
|
self.temporary = None
|
2019-12-17 03:40:08 -05:00
|
|
|
self.ctx = None
|
2019-12-11 04:32:07 -05:00
|
|
|
self._imported_keys = []
|
2019-12-17 03:40:08 -05:00
|
|
|
self._initContext()
|
2019-12-11 04:32:07 -05:00
|
|
|
|
|
|
|
def _initContext(self):
|
|
|
|
if not self.homedir:
|
|
|
|
self.homedir = tempfile.mkdtemp(suffix = '.gpg', prefix = '.aif.')
|
2019-12-17 03:40:08 -05:00
|
|
|
self.temporary = True
|
2019-12-11 04:32:07 -05:00
|
|
|
self.homedir = os.path.abspath(os.path.expanduser(self.homedir))
|
|
|
|
if not os.path.isdir(self.homedir):
|
|
|
|
os.makedirs(self.homedir, exist_ok = True)
|
|
|
|
os.chmod(self.homedir, 0o0700)
|
2019-12-17 03:40:08 -05:00
|
|
|
self.ctx = gpg.Context(home_dir = self.homedir)
|
2019-12-11 04:32:07 -05:00
|
|
|
if self.temporary:
|
2019-12-17 03:40:08 -05:00
|
|
|
self.primary_key = self.createKey('AIF-NG File Verification Key', sign = True, force = True).fpr
|
|
|
|
self.primary_key = self.findKeyByID(self.primary_key, source = 'secret')
|
|
|
|
self.ctx.signers = [self.primary_key]
|
2019-12-11 04:33:15 -05:00
|
|
|
return(None)
|
2019-12-11 04:32:07 -05:00
|
|
|
|
|
|
|
def clean(self):
|
|
|
|
# This is mostly just to cleanup the stuff we did before.
|
|
|
|
self.primary_key = self.primary_key.fpr
|
|
|
|
if self.temporary:
|
|
|
|
self.primary_key = None
|
|
|
|
shutil.rmtree(self.homedir)
|
2019-12-17 03:40:08 -05:00
|
|
|
self.ctx = None
|
2019-12-11 04:33:15 -05:00
|
|
|
return(None)
|
2019-12-11 04:32:07 -05:00
|
|
|
|
|
|
|
def createKey(self, userid, *args, **kwargs):
|
|
|
|
# algorithm=None, expires_in=0, expires=True, sign=False, encrypt=False, certify=False,
|
|
|
|
# authenticate=False, passphrase=None, force=False
|
|
|
|
keyinfo = {'userid': userid,
|
|
|
|
'algorithm': kwargs.get('algorithm', 'rsa4096'),
|
|
|
|
'expires_in': kwargs.get('expires_in'),
|
|
|
|
'sign': kwargs.get('sign', True),
|
|
|
|
'encrypt': kwargs.get('encrypt', False),
|
|
|
|
'certify': kwargs.get('certify', False),
|
|
|
|
'authenticate': kwargs.get('authenticate', False),
|
|
|
|
'passphrase': kwargs.get('passphrase'),
|
|
|
|
'force': kwargs.get('force')}
|
|
|
|
if not keyinfo['expires_in']:
|
|
|
|
del(keyinfo['expires_in'])
|
|
|
|
keyinfo['expires'] = False
|
2019-12-17 03:40:08 -05:00
|
|
|
k = self.ctx.create_key(**keyinfo)
|
|
|
|
return(k)
|
2019-12-11 04:32:07 -05:00
|
|
|
|
|
|
|
def findKey(self, searchstr, secret = False, local = True, remote = True,
|
2019-12-17 03:40:08 -05:00
|
|
|
secret_only = False, keyring_import = False, *args, **kwargs):
|
2019-12-11 04:32:07 -05:00
|
|
|
fltr = 0
|
|
|
|
if secret:
|
|
|
|
fltr = fltr | gpg.constants.KEYLIST_MODE_WITH_SECRET
|
|
|
|
if local:
|
|
|
|
fltr = fltr | gpg.constants.KEYLIST_MODE_LOCAL
|
|
|
|
if remote:
|
|
|
|
fltr = fltr | gpg.constants.KEYLIST_MODE_EXTERN
|
2019-12-17 03:40:08 -05:00
|
|
|
keys = [k for k in self.ctx.keylist(pattern = searchstr, secret = secret_only, mode = fltr)]
|
2019-12-11 04:32:07 -05:00
|
|
|
if keyring_import:
|
|
|
|
self.importKeys(keys, native = True)
|
|
|
|
return(keys)
|
|
|
|
|
2019-12-17 03:40:08 -05:00
|
|
|
def findKeyByID(self, key_id, source = 'remote', keyring_import = False, *args, **kwargs):
|
|
|
|
# So .get_key() CAN get a remote key from a keyserver... but you can't have ANY other keylist modes defined.
|
|
|
|
# Ugh.
|
|
|
|
sources = {'remote': gpg.constants.KEYLIST_MODE_EXTERN,
|
|
|
|
'local': gpg.constants.KEYLIST_MODE_LOCAL,
|
|
|
|
'secret': gpg.constants.KEYLIST_MODE_WITH_SECRET}
|
|
|
|
if source not in sources.keys():
|
|
|
|
raise ValueError('source parameter must be one (and only one) of: {0}'.format(sources.keys()))
|
|
|
|
orig_mode = self.ctx.get_keylist_mode()
|
|
|
|
self.ctx.set_keylist_mode(sources[source])
|
|
|
|
try:
|
|
|
|
key = self.ctx.get_key(key_id, secret = (True if source == 'secret' else False))
|
|
|
|
except gpg.errors.KeyNotFound:
|
|
|
|
key = None
|
|
|
|
self.ctx.set_keylist_mode(orig_mode)
|
|
|
|
if keyring_import and key:
|
|
|
|
self.importKeys(key, native = True)
|
|
|
|
return(key)
|
|
|
|
|
|
|
|
def getKey(self, key_id, secret = False, strict = False, *args, **kwargs):
|
2019-12-11 04:32:07 -05:00
|
|
|
try:
|
|
|
|
getattr(key_id, 'fpr')
|
|
|
|
return(key_id)
|
|
|
|
except AttributeError:
|
|
|
|
if not strict:
|
2019-12-17 03:40:08 -05:00
|
|
|
self.findKeyByID(key_id, keyring_import = True, **kwargs)
|
2019-12-11 04:32:07 -05:00
|
|
|
try:
|
2019-12-17 03:40:08 -05:00
|
|
|
key = self.ctx.get_key(key_id, secret = secret)
|
2019-12-11 04:32:07 -05:00
|
|
|
except gpg.errors.KeyNotFound:
|
|
|
|
key = None
|
|
|
|
return(key)
|
2019-12-11 04:33:15 -05:00
|
|
|
return(None)
|
2019-12-11 04:32:07 -05:00
|
|
|
|
2019-12-17 03:40:08 -05:00
|
|
|
def getKeyFile(self, keyfile, keyring_import = False, *args, **kwargs):
|
2019-12-11 04:32:07 -05:00
|
|
|
keyfile = os.path.abspath(os.path.expanduser(keyfile))
|
|
|
|
with open(keyfile, 'rb') as fh:
|
|
|
|
rawkey_data = fh.read()
|
|
|
|
fh.seek(0, 0)
|
2019-12-17 03:40:08 -05:00
|
|
|
keys = [k for k in self.ctx.keylist(source = fh)]
|
2019-12-11 04:32:07 -05:00
|
|
|
if keyring_import:
|
|
|
|
self.importKeys(keys, native = True)
|
|
|
|
return((keys, rawkey_data))
|
|
|
|
|
2019-12-17 03:40:08 -05:00
|
|
|
def getKeyData(self, keydata, keyring_import = False, *args, **kwargs):
|
2019-12-11 04:32:07 -05:00
|
|
|
orig_keydata = keydata
|
|
|
|
if isinstance(keydata, str):
|
|
|
|
keydata = keydata.encode('utf-8')
|
|
|
|
buf = io.BytesIO(keydata)
|
2019-12-17 03:40:08 -05:00
|
|
|
keys = [k for k in self.ctx.keylist(source = buf)]
|
2019-12-11 04:32:07 -05:00
|
|
|
buf.close()
|
|
|
|
if keyring_import:
|
|
|
|
self.importKeys(keys, native = True)
|
|
|
|
return((keys, orig_keydata))
|
|
|
|
|
2019-12-17 03:40:08 -05:00
|
|
|
def importKeys(self, keydata, native = False, local = True, remote = True, *args, **kwargs):
|
|
|
|
fltr = 0
|
|
|
|
orig_km = None
|
|
|
|
keys = []
|
|
|
|
if local:
|
|
|
|
fltr = fltr | gpg.constants.KEYLIST_MODE_LOCAL
|
|
|
|
if remote:
|
|
|
|
fltr = fltr | gpg.constants.KEYLIST_MODE_EXTERN
|
|
|
|
if self.ctx.get_keylist_mode() != fltr:
|
|
|
|
orig_km = self.ctx.get_keylist_mode()
|
|
|
|
self.ctx.set_keylist_mode(fltr)
|
|
|
|
if not native: # It's raw key data (.gpg, .asc, etc.).
|
|
|
|
formatted_keys = b''
|
|
|
|
if isinstance(keydata, str):
|
|
|
|
formatted_keys += keydata.encode('utf-8')
|
|
|
|
elif isinstance(keydata, list):
|
|
|
|
for k in keydata:
|
|
|
|
if isinstance(k, str):
|
|
|
|
formatted_keys += k.encode('utf-8')
|
|
|
|
else:
|
|
|
|
formatted_keys += k
|
|
|
|
else:
|
|
|
|
formatted_keys += keydata
|
|
|
|
for rslt in self.ctx.key_import(formatted_keys).imports:
|
|
|
|
keys.append(self.ctx.get_key(rslt.fpr))
|
|
|
|
else: # It's a native Key() object (or a list of them).
|
2019-12-11 04:32:07 -05:00
|
|
|
if not isinstance(keydata, list):
|
|
|
|
keydata = [keydata]
|
2019-12-17 03:40:08 -05:00
|
|
|
keys = keydata
|
|
|
|
self.ctx.op_import_keys(keydata)
|
|
|
|
if orig_km:
|
|
|
|
self.ctx.set_keylist_mode(orig_km)
|
|
|
|
for k in keys:
|
|
|
|
self.ctx.key_sign(k, local = True)
|
|
|
|
trusteditor = KeyEditor()
|
|
|
|
self.ctx.interact(k, trusteditor.truster)
|
2019-12-11 04:33:15 -05:00
|
|
|
return(None)
|
2019-12-11 04:32:07 -05:00
|
|
|
|
|
|
|
def verifyData(self, data, keys = None, strict = False, detached = None, *args, **kwargs):
|
|
|
|
results = {}
|
|
|
|
if keys:
|
|
|
|
if not isinstance(keys, list):
|
2019-12-17 03:40:08 -05:00
|
|
|
keys = [self.getKey(keys, source = 'local')]
|
2019-12-11 04:32:07 -05:00
|
|
|
else:
|
2019-12-17 03:40:08 -05:00
|
|
|
keys = [self.getKey(k, source = 'local') for k in keys]
|
2019-12-11 04:32:07 -05:00
|
|
|
if isinstance(data, str):
|
|
|
|
data = data.encode('utf-8')
|
2019-12-17 03:40:08 -05:00
|
|
|
fnargs = {'signed_data': data}
|
2019-12-11 04:32:07 -05:00
|
|
|
if detached:
|
|
|
|
if isinstance(detached, str):
|
|
|
|
detached = detached.encode('utf-8')
|
2019-12-17 03:40:08 -05:00
|
|
|
if not isinstance(detached, bytes) and not hasattr(detached, 'read'):
|
|
|
|
raise TypeError('detached must be bytes or a file-like object (make sure the position is correct!)')
|
|
|
|
fnargs['signature'] = detached
|
2019-12-11 04:32:07 -05:00
|
|
|
if strict:
|
2019-12-17 03:40:08 -05:00
|
|
|
fnargs['verify'] = keys
|
|
|
|
results[None] = self.ctx.verify(**fnargs)
|
2019-12-11 04:32:07 -05:00
|
|
|
else:
|
|
|
|
if keys:
|
|
|
|
for k in keys:
|
2019-12-17 03:40:08 -05:00
|
|
|
_fnargs = copy.deepcopy(fnargs)
|
|
|
|
_fnargs['verify'] = [k]
|
|
|
|
try:
|
|
|
|
print(self.ctx.get_keylist_mode())
|
|
|
|
sigchk = self.ctx.verify(**_fnargs)
|
|
|
|
results[k.fpr] = (True, sigchk[1].results, None)
|
|
|
|
except gpg.errors.MissingSignatures as e:
|
|
|
|
results[k.fpr] = (False, e.results, 'Missing Signature')
|
|
|
|
except gpg.errors.BadSignatures as e:
|
|
|
|
results[k.fpr] = (False, e.results, 'Bad Signature')
|
2019-12-11 04:32:07 -05:00
|
|
|
else:
|
2019-12-17 03:40:08 -05:00
|
|
|
results[None] = self.ctx.verify(**fnargs)
|
2019-12-11 04:32:07 -05:00
|
|
|
return(results)
|
|
|
|
|
|
|
|
def verifyFile(self, filepath, *args, **kwargs):
|
|
|
|
filepath = os.path.abspath(os.path.expanduser(filepath))
|
|
|
|
with open(filepath, 'rb') as fh:
|
|
|
|
results = self.verifyData(fh.read(), **kwargs)
|
|
|
|
return(results)
|