def decrypt(file): gpg_home = find_gpg_keys() if ( gpg_home == ''): print 'GPG keys not found' sys.exit(1) gpg = GPG(gnupghome=gpg_home, use_agent=True) public_keys = gpg.list_keys() key_id = public_keys[0]['keyid'] if ( os.path.isfile(file)): if ( file.endswith('.gpg')): stream = open(file, 'rb') status = gpg.decrypt_file(stream, output=file[:-4]) if ( status.ok): os.remove(file) print file[:-4] + ' succesfully decrypted' else: print file + ' not encrypted' elif ( os.path.isdir(file) ): for root, dirs, files in os.walk(file, topdown=True): for name in files: current_file = (os.path.join(root, name)) if ( current_file.endswith('.gpg')): stream = open(current_file, "rb") status = gpg.decrypt_file(stream, output=current_file[:-4]) if ( status.ok ): os.remove(current_file) print current_file[:-4] + ' successfully decrypted' else: print current_file + ' not encrypted' else: print 'ERROR: file or directory not found'
def encrypt(file): gpg_home = find_gpg_keys() if ( gpg_home == ''): print 'GPG keys not found' sys.exit(1) gpg = GPG(gnupghome=gpg_home, use_agent=True) public_keys = gpg.list_keys() key_id = public_keys[0]['keyid'] if ( os.path.isfile(file)): if ( file.endswith('.gpg')): print file + ' is already encrypted' else: stream = open(file, "rb") status = gpg.encrypt_file(stream, key_id, passphrase='default_key', armor=False, always_trust=True, output=file+'.gpg', symmetric=False) stream.close() if ( status.ok): os.remove(file) print file , ' successfully encrypted' elif (os.path.isdir(file)): for root, dirs, files in os.walk(file, topdown=True): for name in files: current_file = (os.path.join(root, name)) if ( current_file.endswith('.gpg') ): print current_file + ' : is already encrypted' else: stream = open(current_file, "rb") status = gpg.encrypt_file(stream, key_id, armor=True, always_trust=True, symmetric=False, output=current_file+'.gpg') stream.close() if ( status.ok ): os.remove(current_file) print current_file + ' successfully encrypted' else: print 'ERROR, file or directory not found'
def generate_keys(gpg: gnupg.GPG, company_name: str, targer_folder: str): company_path, public_file_name, secret_file_name = __get_absolut_filepath( company_name=company_name) configuration_kwargs = utils.get_configuratation( path=os.path.join(targer_folder, 'configuration')) os.makedirs(company_path, exist_ok=True) gpg_keys = gpg.gen_key_input(**configuration_kwargs.get('array')) key = gpg.gen_key(gpg_keys) ascii_armored_public_keys = gpg.export_keys(key.fingerprint) ascii_armored_private_keys = gpg.export_keys( key.fingerprint, secret=True, passphrase=configuration_kwargs.get('array')['passphrase'], ) with open(public_file_name, 'w') as file: file.write(ascii_armored_public_keys) logger.info(f'Generate file to export to customer done') with open(secret_file_name, 'w') as file: file.write(ascii_armored_public_keys) file.write(ascii_armored_private_keys) logger.info(f'Generate file to use done') _clean_directory(path=settings.PROJECT_NAME)
def encrypt_archive(config, workspace, passcode): narrate("Encrypting the archive") with cd(workspace): run('tar -cf archive.tgz archive', 'soEW') with open('archive.tgz', 'rb') as f: cleartext = f.read() gpg = GPG() encrypted = gpg.encrypt( cleartext, recipients=None, symmetric=True, passphrase=str(passcode), ) if encrypted.ok: with open('archive.tgz.gpg', 'w') as f: f.write(str(encrypted)) else: raise EncryptionFailed(encrypted) rm('archive.tgz', 'archive') script = workspace / 'decrypt.sh' script.write_text('''\ #!/bin/sh # Decrypts the archive. gpg -d -o - archive.tgz.gpg | tar xvf - ''') chmod(0o700, script, workspace / 'archive.tgz.gpg') narrate(f"Local archive '{workspace.name}' created.")
def do_job_unit(self, event, corpus, unit, **kwargs): preroll = kwargs.get("preroll", 0) for i, (domain, count, path, url) in enumerate( self.get_chunk_info_paths_urls(event, corpus, preroll=preroll)): if i != unit: continue gpg = GPG() #http = urllib3.PoolManager() parent = os.path.dirname(path) if not os.path.exists(parent): try: os.makedirs(parent) except OSError as e: if e.errno == errno.EEXIST and os.path.isdir(parent): pass retries = 3 while 1: try: r = requests.get(url, timeout=30) with open(path, u'wb') as f: f.write(str(gpg.decrypt(r.content))) break except requests.exceptions.ConnectionError: retries -= 1 if retries == 0: break except urllib3.exceptions.ReadTimeoutError: retries -= 1 if retries == 0: break
def _encrypt(self, plain): # test if we have public keys for all recipients available_recipients = [] keys = [] for key in Key.objects.all(): keys.append(key) available_recipients.extend(key.addresses.split(', ')) logger.debug("available_recipients: %s", available_recipients) if not all(recipient in available_recipients for recipient in self.recipients()): logger.error( "Public key not present for at least one of these recipients: %s", self.recipients()) raise GPGException( "Public key not present for at least one recipient") # encryption with TemporaryDirectory() as temp_dir: gpg = GPG(gnupghome=temp_dir) for key in keys: gpg.import_keys(key.key) res = gpg.encrypt(plain, self.recipients(), always_trust=True) if not res: handle_gpg_error(res, 'encryption') return smart_text(res)
def clean_key(self): """ Raises ValidationError if the entered key is invalid or includes a GPG private key. """ data = self.cleaned_data['key'] with TemporaryDirectory() as temp_dir: gpg_keychain = GPG(gnupghome=temp_dir) res = gpg_keychain.import_keys(data) if not res: errors = [ forms.ValidationError(_("Invalid key."), code='invalid') ] for attr in ['status', 'stderr']: # not all fields are always present if hasattr(res, attr): errors.append( forms.ValidationError("%(name)s: %(value)s", params={ 'name': attr, 'value': getattr(res, attr) }, code=attr)) raise forms.ValidationError(errors) if len(gpg_keychain.list_keys( True)) > 0: # check existance of private keys raise forms.ValidationError(_( "Import public keys only, no private keys! " "You should consider the private key(s) compromised."), code='private_key') return data
def _get_gpg_output_for_pubkey_file(self, pubkey_file): with TemporaryDirectory() as temp_gpg_home: gpg = GPG(gnupghome=temp_gpg_home) with open(pubkey_file, 'rb') as pubkey_fh: gpg.import_keys(pubkey_fh.read()) gpg_stdout = check_output([ 'gpg', '--homedir', temp_gpg_home, '--keyid-format', '0xlong', '--with-fingerprint', '--list-options', 'show-uid-validity', '--verify-options', 'show-uid-validity', # '--list-sigs', # Public keys for signatures over the UIDs might not be present. '--list-public-keys' ]).decode('utf-8') truncated_lines = [] in_header = True for line in gpg_stdout.split('\n'): # OpenPGP subkeys might be subject to more frequent change # and are expected to not always be updated in the keyring. # You might need to update OpenPGP subkeys from keyservers. if not in_header and not re.match(r'sub\s', line): truncated_lines.append(line) if re.match(r'^---------', line): in_header = False return '\n'.join(truncated_lines)
def __init__(self, receiver_desc): """ every time is needed, a new keyring is created here. """ if receiver_desc.has_key('gpg_key_status') and \ receiver_desc['gpg_key_status'] != Receiver._gpg_types[1]: # Enabled log.err( "Requested GPG initialization for a receiver without GPG configured! %s" % receiver_desc['username']) raise Exception("Requested GPG init for user without GPG [%s]" % receiver_desc['username']) try: temp_gpgroot = os.path.join(GLSetting.gpgroot, "%s" % xeger(r'[A-Za-z0-9]{8}')) os.makedirs(temp_gpgroot, mode=0700) self.gpgh = GPG(gnupghome=temp_gpgroot, options=['--trust-model', 'always']) except Exception as excep: log.err("Unable to instance GPG object: %s" % excep) raise excep self.receiver_desc = receiver_desc log.debug("GPG object initialized for receiver %s" % receiver_desc['username'])
def finish_clone_pass(message, bot, path_to_user_folder): t_str = 'test_ur_crappy_password_str' decrypt = None try: gpg = GPG() encrypt = gpg.encrypt(t_str, recipients='user_'+str(message.chat.id)) decrypt = gpg.decrypt(str(encrypt), passphrase=message.text) system('echo RELOADAGENT | gpg-connect-agent') except: msg = bot.send_message(message.chat.id, 'Произошла ошибка.') del_mess(msg, bot, 8) return if str(decrypt) == t_str: try: with open(path_to_user_folder+'/user_data/Nothing.txt', 'w') as f: f.write(message.text) msg = bot.send_message(message.chat.id, 'Пароль сохранен.', reply_markup = types.ReplyKeyboardRemove(selective=False)) del_mess(msg, bot, 8) return except: msg = bot.send_message(message.chat.id, 'Произошла ошибка.', reply_markup = types.ReplyKeyboardRemove(selective=False)) del_mess(msg, bot, 8) return else: msg = bot.send_message(message.chat.id, 'Пароль не верен.') msg_handler = bot.send_message(message.chat.id, 'Введите пароль от нового ключа, я его сохраню.', reply_markup = types.ReplyKeyboardRemove(selective=False)) bot.register_next_step_handler(msg_handler, lambda msg: finish_clone_pass(msg, bot, path_to_user_folder))
def __init__(self, tmpdir: str, keys_dir: str = 'data/keys') -> None: # GPG needs the homedir to have limited permissions os.chmod(tmpdir, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) self.homedir = tmpdir self.gpg = GPG(gnupghome=tmpdir) self.keys = self.import_keys(keys_dir)
def do_job_unit(self, event, corpus, unit, **kwargs): preroll = kwargs.get("preroll", 0) for i, (domain, count, path, url) in enumerate(self.get_chunk_info_paths_urls( event, corpus, preroll=preroll)): if i != unit: continue gpg = GPG() #http = urllib3.PoolManager() parent = os.path.dirname(path) if not os.path.exists(parent): try: os.makedirs(parent) except OSError as e: if e.errno == errno.EEXIST and os.path.isdir(parent): pass retries = 3 while 1: try: r = requests.get(url, timeout=30) with open(path, u'wb') as f: f.write(str(gpg.decrypt(r.content))) break except requests.exceptions.ConnectionError: retries -= 1 if retries == 0: break except urllib3.exceptions.ReadTimeoutError: retries -= 1 if retries == 0: break
def gpg_verify(gpg_signature, filename): """ Verify that the signature is valid for the content of the filename """ gpg_sign_stream = BytesIO(gpg_signature) gpg_keyring_fn = join(realpath(dirname(__file__)), "trusted", "keyring.gpg") gpg = GPG(keyring=gpg_keyring_fn) return gpg.verify_file(gpg_sign_stream, filename)
def write_empty_config(self, config, conffile): rootdir = BaseDirectory.save_config_path('tuyau') with file(conffile, 'wb') as fp: config.write(fp) g = GPG(gnupghome=os.path.join(rootdir, 'gnupg')) g.list_keys()
def get_expirations(keylist): """ This function is not implemented in GPG object class because need to operate on the whole keys """ atfork() try: temp_gpgroot = os.path.join(GLSetting.gpgroot, "-expiration_check-%s" % random.randint(0, 0xFFFF) ) os.makedirs(temp_gpgroot, mode=0700) gpexpire= GPG(gnupghome=temp_gpgroot, options="--trust-model always") except Exception as excep: log.err("Unable to setup expiration check environment: %s" % excep) raise excep try: for key in keylist: gpexpire.import_keys(key) except Exception as excep: log.err("Error in GPG import_keys: %s" % excep) raise excep try: all_keys = gpexpire.list_keys() except Exception as excep: log.err("Error in GPG list_keys: %s" % excep) raise excep expirations = {} for ak in all_keys: expirations.update({ ak['fingerprint'] : ak['date']}) return expirations
def execute(self): gpg_home = os.path.join(os.path.expanduser('~'), '.gnupg/') default_recpipient = os.environ['DEFAULT_RECIPIENT'] if not default_recpipient: self.fm.notify( 'DEFAULT_RECIPIENT environment variable must be set') return gpg = GPG(gpgbinary='/usr/bin/gpg', gnupghome=gpg_home) paths = [ os.path.basename(f.path) for f in self.fm.thistab.get_selection() ] for p in paths: if os.path.isdir(p): new_p = self.tardir(p) run(['rm', '-rf', p]) p = new_p with open(p, 'rb') as f: enc = gpg.encrypt_file(f, default_recpipient) with open(p + '.gpg', 'wb+') as out: out.write(enc.data) if os.path.isfile(p): os.remove(p)
def configure_gpg(self, key: str, password: Optional[str]) -> None: """Configure the repo to sign tags with GPG.""" home = os.environ["GNUPGHOME"] = mkdtemp(prefix="tagbot_gpg_") os.chmod(home, S_IREAD | S_IWRITE | S_IEXEC) logger.debug(f"Set GNUPGHOME to {home}") gpg = GPG(gnupghome=home, use_agent=True) import_result = gpg.import_keys(self._maybe_decode_private_key(key), passphrase=password) if import_result.sec_imported != 1: logger.warning(import_result.stderr) raise Abort("Importing key failed") key_id = import_result.fingerprints[0] logger.debug(f"GPG key ID: {key_id}") if password: # Sign some dummy data to put our password into the GPG agent, # so that we don't need to supply the password when we create a tag. sign_result = gpg.sign("test", passphrase=password) if sign_result.status != "signature created": logger.warning(sign_result.stderr) raise Abort("Testing GPG key failed") # On Debian, the Git version is too old to recognize tag.gpgSign, # so the tag command will need to use --sign. self._git._gpgsign = True self._git.config("tag.gpgSign", "true") self._git.config("user.signingKey", key_id)
def send_mail(self, subject, body): if self.gpg_key: with TemporaryDirectory() as tmp_dir: gpg = GPG(homedir=tmp_dir) key = gpg.import_keys(self.gpg_key) body = str(gpg.encrypt(body, *key.fingerprints)) send_mail(subject, body, settings.EMAIL_ADDRESS, [self.email])
def get_expirations(keylist): """ This function is not implemented in GPG object class because need to operate on the whole keys """ try: temp_gpgroot = os.path.join( GLSetting.gpgroot, "-expiration_check-%s" % xeger(r'[A-Za-z0-9]{8}')) os.makedirs(temp_gpgroot, mode=0700) gpexpire = GPG(gnupghome=temp_gpgroot, options=['--trust-model', 'always']) except Exception as excep: log.err("Unable to setup expiration check environment: %s" % excep) raise excep try: for key in keylist: gpexpire.import_keys(key) except Exception as excep: log.err("Error in GPG import_keys: %s" % excep) raise excep try: all_keys = gpexpire.list_keys() except Exception as excep: log.err("Error in GPG list_keys: %s" % excep) raise excep expirations = {} for ak in all_keys: expirations.update({ak['fingerprint']: ak['date']}) return expirations
def __init__(self, tempdirprefix=None): """ every time is needed, a new keyring is created here. """ if tempdirprefix is None: tempdir = tempfile.mkdtemp() else: tempdir = tempfile.mkdtemp(prefix=tempdirprefix) try: gpgbinary = 'gpg' if os.path.exists('/usr/bin/gpg1'): gpgbinary = 'gpg1' self.gnupg = GPG(gpgbinary=gpgbinary, gnupghome=tempdir, options=['--trust-model', 'always']) self.gnupg.encoding = "UTF-8" except OSError as excep: log.err("Critical, OS error in operating with GnuPG home: %s", excep) raise except Exception as excep: log.err("Unable to instance PGP object: %s" % excep) raise
def finish_auth_pass(message, bot): t_str = 'test_ur_crappy_password_str' decrypt = None try: gpg = GPG() encrypt = gpg.encrypt(t_str, recipients='user_' + str(message.chat.id)) decrypt = gpg.decrypt(str(encrypt), passphrase=str(message.text)) system('echo RELOADAGENT | gpg-connect-agent') except: msg = bot.send_message(message.chat.id, 'Произошла ошибка.') del_mess(msg, bot, 4) result_available.set() if str(decrypt) == t_str: global pas msg = bot.send_message(message.chat.id, 'Вы аутентифицировались.') pas = str(message.text) del_mess(msg, bot, 4) result_available.set() else: msg = bot.send_message(message.chat.id, 'Пароль не верен.') del_mess(msg, bot, 4) result_available.set()
def get_gpg_pwd(apistatus, userid_status, mfa, userid, g_home, g_pass): """Returns gpg password if all inputs are valid. Keyword arguments: apistatus - The true/false return value from the check_api_key function. userid_stauts - The true/false return value from the check_userid function. mfa - The true/false return value from the check_totp function. userid - The userid that corresponds (key:value) to sensitive data that is being retrieved. g_home - The GPG home directory for this application, i.e. export |grep GNUPGHOME. g_pass - The password for the GPG private key. Output: The function returns the sensitive data that corresponds to the userid.""" # Performing input validation. if not validate_userid(userid): return 1 # Checking login status and that the API key is authorized to # access the userid. if apistatus and userid_status and mfa: gpg_file = open(c_text, 'r', encoding='ascii').read().strip('\n') g = GPG(homedir=g_home) gpg_data = str(g.decrypt(gpg_file, passphrase=g_pass)).split('\n') for line in gpg_data: reg_search = search(r'(^' + userid + ': )(.+)', line) if reg_search: return reg_search.group(2) else: return False
def getGPG(): global lunch_gpg if not lunch_gpg: from gnupg import GPG gbinary = getBinary("gpg", "bin") if not gbinary: raise Exception("GPG not found") ghome = os.path.join(get_settings().get_main_config_dir(),"gnupg") if not locale.getpreferredencoding(): # Fix for GnuPG on Mac # TODO will this work on systems without English locale? os.putenv("LANG", "en_US.UTF-8") if not locale.getpreferredencoding(): # Fix for GnuPG on Mac # TODO will this work on systems without English locale? os.putenv("LANG", "en_US.UTF-8") try: if getPlatform() == PLATFORM_WINDOWS: lunch_gpg = GPG("\""+gbinary+"\"",ghome) else: lunch_gpg = GPG(gbinary,ghome) if not lunch_gpg.encoding: lunch_gpg.encoding = 'utf-8' except Exception, e: raise Exception("GPG not working: "+str(e))
def verify_gpg_signature(f): gpg = GPG(homedir='~/.gnupg') # search public key 0x90C8019E36C2E964 bitcoin_core_pgp_key_found = False keys = gpg.list_keys() for key in keys: if key['keyid'] == '90C8019E36C2E964': bitcoin_core_pgp_key_found = True if not bitcoin_core_pgp_key_found == True: print( '* Warning: bitcoin-core GPG key not found, trying to find and import...' ) import_key = gpg.recv_keys('90C8019E36C2E964', keyserver='hkp://pool.sks-keyservers.net') print('* Status: ' + import_key.summary()) print('* Fingerprint: ' + import_key.fingerprints[0]) with open(f) as fi: verif = gpg.verify_file(fi) print('* Verifying ' + f + ': ' + verif.status) if not verif.valid: print('* Impossible to compare checksums, quitting!') return verif.valid
def clean(self): gpg = GPG(gpgbinary=settings.GNUPGBINARY, gnupghome=settings.GNUPGHOME) key = gpg.get_key(self.fingerprint) if key['ownertrust'] in settings.TRUST_LEVELS: self.is_trusted = True else: self.is_trusted = False self.save()
def test_addresses_for_key(self): """Test email address extraction from GPG public keys.""" with TemporaryDirectory() as temp_dir: gpg_keychain = GPG(gnupghome=temp_dir) res = gpg_keychain.import_keys(self.key.key) self.assertTrue(res) self.assertEqual(len(res.results), 1) self.assertEqual(addresses_for_key(gpg_keychain, res.results[0]), ['*****@*****.**'])
def init(self, bundle): if not 'username' in bundle: return False self.gpg = GPG(use_agent=True) self.gpgmail = GPGMail(self.gpg) self.gmail = Gmail(bundle['username']) self.initialized = True return {'version': VERSION}
def gnupg_key_fingerprint(gnupg_instance: GPG, private_gpg_key: str): keys_imported = gnupg_instance.import_keys(private_gpg_key) key_fingerprint = keys_imported.fingerprints[0] yield key_fingerprint if key_fingerprint in gnupg_instance.list_keys(secret=True).fingerprints: remove_gpg_key_pair(gpg_binary=gnupg_instance.gpgbinary, fingerprint=key_fingerprint)
def __init__(self, gpg=None): if gpg: self.gpg = gpg else: self.gpg = GPG(gpgbinary="gpg2", use_agent=True) GPGLogger.setLevel(logging.DEBUG) self.logger = logging.getLogger('GPGMail')
def __call__(self): fileName = as_human_readable(self.get_chosen_files()[0]) gpg = GPG() myPass, ok = show_prompt('Passphrase') # https://stackoverflow.com/questions/4444923/get-filename-without-extension-in-python fileNameOut, ok = show_prompt('Target', default=os.path.splitext(fileName)[0]) with open(fileName, 'rb') as f: status = gpg.decrypt_file(f, passphrase=myPass, output=fileNameOut) show_alert('Status: ' + status.status)
def sign(self, dist): self._reprepro('export %s' % dist) gpg = GPG(gnupghome=conf('repository.gpghome')) filename = os.path.join(self.path, 'dists/%s/Release' % dist) detach_file = filename + '.gpg' try: os.unlink(detach_file) except: pass result = gpg.sign_file(file(filename, 'r'), keyid=conf('repository.signkey'), outputfile=detach_file)
def decrypt(data: str, gpg: GPG) -> str: """ Decrypt `data` with `gpg` and return its value. """ result = gpg.decrypt(data, always_trust=True) if not result.ok: raise DecryptionError(result.status) else: return str(gpg.decrypt(data, always_trust=True))
def get_gpg(): gpg_kwargs = { 'gnupghome': GNUPG_HOME, } if GNUPG_BINARY: gpg_kwargs['gpgbinary'] = GNUPG_BINARY gpg = GPG(**gpg_kwargs) if GNUPG_ENCODING is not None: gpg.encoding = GNUPG_ENCODING return gpg
def clean_key(self): """ Validate the key contains an email address. """ key = self.cleaned_data["key"] gpg = GPG(gnupghome=GNUPG_HOME) result = gpg.import_keys(key) if result.count == 0: raise forms.ValidationError(_("Invalid Key")) return key
def sign(self, dist): self._reprepro('export %s' % dist) gpg = GPG() filename = os.path.join(self.path, 'dists/%s/Release' % dist) detach_file = filename + '.gpg' try: os.unlink(detach_file) except: pass result = gpg.sign_file(file(filename, 'r'), keyid=conf('repository.signkey'), outputfile=detach_file)
class reqPGP(object): def __init__(self, path=None): self.gpg = GPG(gpgbinary=('../gpg.exe' if osName == 'nt' else 'gpg')) if not path: try: self.path = environ["HOME"] + '/' except KeyError: self.path = environ["HOMEPATH"] + '\\' else: if path[-1] != '\\' and osName == 'nt': path += '\\' elif path[-1] != '/' and osName == 'posix': path += '/' self.path = path def genKey(self, account, passphrase): input_data = self.gpg.gen_key_input( name_email=account, passphrase=passphrase) self.gpg.gen_key(input_data) def encryptFile(self, account, data): encryptedData = str(self.gpg.encrypt(data, account)) with open(self.path + '.' + account + '.req', 'w') as f: f.write(encryptedData) def decryptFile(self, account, passphrase): with open(self.path + '.' + account + '.req', 'rb') as f: decryptedData = str(self.gpg.decrypt_file(f, passphrase=passphrase)) return decryptedData def deleteKey(self, keyId): self.gpg.delete_keys(keyId, True) self.gpg.delete_keys(keyId)
def extract_content(path, keyring, output_dir, output_ext): """ Use the keyring to decrypt a document """ name = os.path.splitext(os.path.basename(path))[0] gpg = GPG(gnupghome=keyring) new_path = os.path.join(output_dir, '.'.join([name, output_ext])) try: with open(path, 'rb') as content: data = gpg.decrypt(content.read(), output=new_path) except OSError: raise DecryptionError("Could not open '%s'" % path, path) return new_path
def _generate_key(username): gpg = GPG() key_input = gpg.gen_key_input(key_type="RSA", key_length=1024, name_email=username+"@node.org", name_real=username) entropy_thread = Process(target=generate_entropy) entropy_thread.start() key = gpg.gen_key(key_input) entropy_thread.terminate() keys = gpg.list_keys(True) for k in keys: if k.get("fingerprint") == key.fingerprint: return k['keyid']
def save(self, *args, **kwargs): super(Key, self).save(*args, **kwargs) gpg = GPG(gnupghome=GNUPG_HOME) result = gpg.import_keys(self.key) addresses = [] for key in result.results: addresses.extend(addresses_for_key(gpg, key)) self.addresses = ",".join(addresses) for address in addresses: address, _ = Address.objects.get_or_create(address=address) address.use_asc = self.use_asc address.save()
class WebofTrustVisualization(): def __init__(self, folder, pubkey=None): self.folder = folder self.gpg2_dir = os.path.join(folder, "gnupg") if not os.path.exists(self.folder): os.mkdir(self.folder) if os.path.exists(os.path.join(self.gpg2_dir, "pubring.gpg")) and not pubkey: print ("Continuing...") self.getNumber() self.gpg2 = GPG(gpgbinary="gpg2", gnupghome=self.gpg2_dir) elif not os.path.exists(self.gpg2_dir) and pubkey: print ("Initializing with key {}...".format(pubkey)) os.mkdir(self.gpg2_dir, mode=0o700) self.gpg2 = GPG(gpgbinary="gpg2", gnupghome=self.gpg2_dir) self.recv_keys(pubkey) self.number = 0 self.saveNumber() else: raise InvalidArgumentException def recv_keys(self, *pubkeys): self.gpg2.recv_keys("pgp.mit.edu", *pubkeys) def gendot(self): with open(os.path.join(self.folder, "{}.dot".format(self.number)), "w") as dot: with Popen(self.gpg2.make_args(["--list-sigs"], False), stdout=PIPE) as gpg2: Popen(["sig2dot", "-a"], stdin=gpg2.stdout, stdout=dot).wait() def draw(self, format="ps"): with open("{}.{}".format(os.path.join(self.folder, str(self.number)), format), "w") as drawing: Popen(["dot", "-T{}".format(format), "{}.dot".format(os.path.join(self.folder, str(self.number)))], stdout=drawing).wait() def nextRound(self): sigs_missing = [] print ("gpg2") with Popen(self.gpg2.make_args(["--list-sigs"], False), stdout=PIPE, env={"LANG": "C.UTF-8"}) as gpg2: for sig in gpg2.stdout.read().splitlines(): if b"[User ID not found]" in sig: for elem in sig.split(): if len(elem) == 8: if elem.decode() not in sigs_missing: #we need each key only once sigs_missing.append(elem.decode()) self.number += 1 #better safe than sorry self.saveNumber() self.recv_keys(*sigs_missing) def getNumber(self): with open(os.path.join(self.folder, "number"), "r") as number: self.number = int(number.read().strip()) def saveNumber(self): with open(os.path.join(self.folder, "number"), "w") as number: number.write(str(self.number))
def forward_change(apps, schema_editor): Key = apps.get_model('email_extras', 'Key') Address = apps.get_model('email_extras', 'Address') for key in Key.objects.all(): addresses = Address.objects.filter(address__in=key.addresses.split(',')) addresses.update(key=key) gpg = GPG(gnupghome=GNUPG_HOME) result = gpg.import_keys(key.key) key.fingerprint = result.fingerprints[0] key.save()
def import_key(keypath, keyring): """ Imports all keys from specified directory This function is idempotent, so importing the same key multiple times will always succeed. :param keypath: path to armored key file :param keyring: directory of the keyring """ gpg = GPG(gnupghome=keyring) try: with open(keypath, 'r') as keyfile: result = gpg.import_keys(keyfile.read()) except OSError: raise KeyImportError("Could not open '%s'" % keypath, keypath) if result.count == 0: raise KeyImportError("Could not import '%s'" % keypath, keypath)
def sign(config, s_filename): """sign the package""" gpg_home = config.get('gpg_dir', '/var/lib/sachannelupdate/gnupg') gpg_pass = config.get('gpg_passphrase') gpg_keyid = config.get('gpg_keyid') gpg = GPG(gnupghome=gpg_home) try: plaintext = open(s_filename, 'rb') signature = gpg.sign_file( plaintext, keyid=gpg_keyid, passphrase=gpg_pass, detach=True) with open('%s.asc' % s_filename, 'wb') as handle: handle.write(str(signature)) finally: if 'plaintext' in locals(): plaintext.close()
def save(self, *args, **kwargs): with TemporaryDirectory() as temp_dir: gpg_keychain = GPG(gnupghome=temp_dir) res = gpg_keychain.import_keys(self.key) if not res: handle_gpg_error(res, 'import') if len(gpg_keychain.list_keys(True)) > 0: raise GPGException("Will not import GPG private key!") addresses = [] for key in res.results: addresses.extend(addresses_for_key(gpg_keychain, key)) self.addresses = ', '.join(addresses) operation = "Updating" if self.pk else "Creating" logger.info("%s GPG key for: %s", operation, self.addresses) super(Key, self).save(*args, **kwargs)
def save_model(self, request, obj, form, change): """ import the key and parse the addresses from it and save them and omit the super save_model call so as to never save the key instance """ gpg = GPG(gnupghome=GNUPG_HOME) result = gpg.import_keys(obj.key) if result.count == 0: raise forms.ValidationError("Invalid Key") else: addresses = [] for key in result.results: addresses.extend(addresses_for_key(gpg, key)) obj.addresses = ",".join(addresses) for address in addresses: Address.objects.get_or_create(address=address)
def __init__(self, name, dbname='axolotl.db', dbpassphrase='', user_pathstring='~'): self.ratchetKey = None self.ratchetPKey = None self.name = name self.db = None self.mode = None self.staged_HK_mk = None self.state = None self.handshakeKey = None self.handshakePKey = None self.storeTime = None user_path = os.path.expanduser(user_pathstring) keyring = [user_path + '/.gnupg/pubring.gpg'] secret_keyring = [user_path + '/.gnupg/secring.gpg'] self.dbname = user_path + '/tmp/pyaxo_db/' + dbname self.gpg = GPG(gnupghome=user_path + '/.axolotl', gpgbinary='gpg', keyring=keyring, secret_keyring=secret_keyring, options=['--throw-keyids', '--personal-digest-preferences=sha256', '--s2k-digest-algo=sha256']) self.gpg.encoding = 'utf-8' if dbpassphrase != '' or dbpassphrase is None: self.dbpassphrase = dbpassphrase else: self.dbpassphrase = getpass( 'Database passphrase for ' + self.name + ': ').strip() self.db_init()
class GpgExtractor(StoqExtractorPlugin): def __init__(self): super().__init__() def activate(self, stoq): self.stoq = stoq super().activate() if not os.path.exists(self.gpg_home): self.stoq.exception("GPG Home is not defined! Skipping...") self.gpg = GPG(gnupghome=self.gpg_home, gpgbinary=self.gpg_bin, keyring=self.public_keyring, secret_keyring=self.secret_keyring) def extract(self, payload, **kwargs): """ Decrypt content from provided payload :param bytes payload: Payload to be decrypted :param **kwargs kwargs: Additional attributes (unused) :returns: Decrypted payload :rtype: list of tuples """ passphrase = None always_trust = False if self.passphrase: passphrase = self.passphrase if self.always_trust: always_trust = self.always_trust # Ensure the payload is a ByesIO object payload_object = BytesIO(payload) # Decrypt the payload and return a file object decrypted_payload = self.gpg.decrypt_file(payload_object, passphrase=passphrase, always_trust=always_trust) content = decrypted_payload.data if content: meta = {} meta['size'] = len(content) # Return the decrypted payload return [(meta, content)] else: self.stoq.log.error("Unable to decrypt payload: {}".format(kwargs)) return None
def read_key(path, gpg_bin, gpg_opts): """Read and decrypt a single key file. :param str path: The path to the key to decrypt. :param str gpg_bin: The path to the gpg binary. :param list gpg_opts: The options for gpg. :rtype: str :returns: The unencrypted content of the file at `path`. """ gpg = GPG(gpgbinary=gpg_bin, options=gpg_opts) with open(path, 'rb') as key_file: return str(gpg.decrypt_file(key_file))
def gpg_keys(self): """ The GPG keyring path and list of key IDs. :return: A tuple of: (path, key_ids) The *path* is the absolute path to a keyring. The *key_ids* is a list of key IDs added to the keyring. :rtype: tuple """ home = self.working_dir path = os.path.join(home, 'pubring.gpg') key_list = self.config.get(constants.IMPORTER_CONFIG_KEY_GPG_KEYS, []) gpg = GPG(gnupghome=home) map(gpg.import_keys, key_list) key_ids = [key['keyid'] for key in gpg.list_keys()] return path, key_ids
def send_mail(subject, body_text, addr_from, addr_to, fail_silently=False, attachments=None, body_html=None): """ Sends a multipart email containing text and html versions which are encrypted for each recipient that has a valid gpg key installed. """ # Allow for a single address to be passed in. if not hasattr(addr_to, "__iter__"): addr_to = [addr_to] # Obtain a list of the recipients that have gpg keys installed. valid_key_addresses = [] if USE_GNUPG: queryset = Address.objects.filter(address__in=addr_to) valid_key_addresses = queryset.values_list("address", flat=True) # Create the gpg object. if valid_key_addresses: gpg = GPG(gnupghome=GNUPG_HOME) gpg_kwargs = {} if ALWAYS_TRUST: gpg_kwargs.update({'always_trust':ALWAYS_TRUST}) # Encrypts body if recipient has a gpg key installed. encrypt_if_key = lambda body, addr: (body if addr not in valid_key_addresses else unicode(gpg.encrypt(body, addr, **gpg_kwargs))) # Load attachments and create name/data tuples. attachments_parts = [] if attachments is not None: for attachment in attachments: with open(attachment, "rb") as f: attachments_parts.append((basename(attachment), f.read())) # Send emails. for addr in addr_to: msg = EmailMultiAlternatives(subject, encrypt_if_key(body_text, addr), addr_from, [addr]) if body_html is not None: msg.attach_alternative(encrypt_if_key(body_html, addr), "text/html") for parts in attachments_parts: msg.attach(parts[0]+'.asc' if ADD_EXTENSION else parts[0], encrypt_if_key(parts[1], addr)) msg.send(fail_silently=fail_silently)
def write_key(path, key_data, gpg_bin, gpg_opts): """Encrypt and write a single key file. :param str path: The path to the key to decrypt. :param str gpg_bin: The path to the gpg binary. :param list gpg_opts: The options for gpg. """ gpg = GPG(gpgbinary=gpg_bin, options=gpg_opts) gpg_recipients = _get_gpg_recipients(path) # pass always ends it's files with an endline if not key_data.endswith('\n'): key_data += '\n' key_data_enc = gpg.encrypt(key_data, gpg_recipients).data with open(path, 'wb') as key_file: key_file.write(key_data_enc)
def __init__(self, folder, pubkey=None): self.folder = folder self.gpg2_dir = os.path.join(folder, "gnupg") if not os.path.exists(self.folder): os.mkdir(self.folder) if os.path.exists(os.path.join(self.gpg2_dir, "pubring.gpg")) and not pubkey: print ("Continuing...") self.getNumber() self.gpg2 = GPG(gpgbinary="gpg2", gnupghome=self.gpg2_dir) elif not os.path.exists(self.gpg2_dir) and pubkey: print ("Initializing with key {}...".format(pubkey)) os.mkdir(self.gpg2_dir, mode=0o700) self.gpg2 = GPG(gpgbinary="gpg2", gnupghome=self.gpg2_dir) self.recv_keys(pubkey) self.number = 0 self.saveNumber() else: raise InvalidArgumentException