1 # -*- coding: utf-8 -*-
3 # Copyright (C) 2013 LEAP
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 A GPG wrapper used to handle OpenPGP keys.
22 This is a temporary class that will be superseded by the a revised version of
39 Handle status messages for --list-packets.
42 def __init__(self, gpg):
44 Initialize the packet listing handling class.
46 :param gpg: GPG object instance.
52 self.need_passphrase = None
53 self.need_passphrase_sym = None
54 self.userid_hint = None
56 def handle_status(self, key, value):
58 Handle one line of the --list-packets status message.
60 :param key: The status message key.
62 :param value: The status message value.
65 # TODO: write tests for handle_status
69 # This will only capture keys in our keyring. In the future we
70 # may want to include multiple unknown keys in this list.
71 self.key, _, _ = value.split()
72 if key == 'NEED_PASSPHRASE':
73 self.need_passphrase = True
74 if key == 'NEED_PASSPHRASE_SYM':
75 self.need_passphrase_sym = True
76 if key == 'USERID_HINT':
77 self.userid_hint = value.strip().split()
80 class GPGWrapper(gnupg.GPG):
82 This is a temporary class for handling GPG requests, and should be
83 replaced by a more general class used throughout the project.
86 GNUPG_HOME = os.environ['HOME'] + "/.config/leap/gnupg"
87 GNUPG_BINARY = "/usr/bin/gpg" # this has to be changed based on OS
89 def __init__(self, gpgbinary=GNUPG_BINARY, gnupghome=GNUPG_HOME,
90 verbose=False, use_agent=False, keyring=None, options=None):
92 Initialize a GnuPG process wrapper.
94 :param gpgbinary: Name for GnuPG binary executable.
95 :type gpgbinary: C{str}
96 :param gpghome: Full pathname to directory containing the public and
99 :param keyring: Name of alternative keyring file to use. If specified,
100 the default keyring is not used.
101 :param verbose: Should some verbose info be output?
103 :param use_agent: Should pass `--use-agent` to GPG binary?
104 :type use_agent: bool
105 :param keyring: Path for the keyring to use.
107 @options: A list of additional options to pass to the GPG binary.
110 @raise: RuntimeError with explanation message if there is a problem
113 # XXX: options isn't always supported, so removing for the time being
114 gnupg.GPG.__init__(self, gnupghome=gnupghome, gpgbinary=gpgbinary,
115 verbose=verbose, use_agent=use_agent,
116 keyring=keyring)#, options=options)
117 self.result_map['list-packets'] = ListPackets
119 def find_key_by_email(self, email, secret=False):
121 Find user's key based on their email.
123 :param email: Email address of key being searched for.
125 :param secret: Should we search for a secret key?
128 :return: The fingerprint of the found key.
131 for key in self.list_keys(secret=secret):
132 for uid in key['uids']:
133 if re.search(email, uid):
135 raise LookupError("GnuPG public key for email %s not found!" % email)
137 def find_key_by_subkey(self, subkey, secret=False):
139 Find user's key based on a subkey fingerprint.
141 :param email: Subkey fingerprint of the key being searched for.
143 :param secret: Should we search for a secret key?
146 :return: The fingerprint of the found key.
149 for key in self.list_keys(secret=secret):
150 for sub in key['subkeys']:
154 "GnuPG public key for subkey %s not found!" % subkey)
156 def find_key_by_keyid(self, keyid, secret=False):
158 Find user's key based on the key ID.
160 :param email: The key ID of the key being searched for.
162 :param secret: Should we search for a secret key?
165 :return: The fingerprint of the found key.
168 for key in self.list_keys(secret=secret):
169 if keyid == key['keyid']:
172 "GnuPG public key for keyid %s not found!" % keyid)
174 def find_key_by_fingerprint(self, fingerprint, secret=False):
176 Find user's key based on the key fingerprint.
178 :param email: The fingerprint of the key being searched for.
180 :param secret: Should we search for a secret key?
183 :return: The fingerprint of the found key.
186 for key in self.list_keys(secret=secret):
187 if fingerprint == key['fingerprint']:
190 "GnuPG public key for fingerprint %s not found!" % fingerprint)
192 def encrypt(self, data, recipient, sign=None, always_trust=True,
193 passphrase=None, symmetric=False):
195 Encrypt data using GPG.
197 :param data: The data to be encrypted.
199 :param recipient: The address of the public key to be used.
201 :param sign: Should the encrypted content be signed?
203 :param always_trust: Skip key validation and assume that used keys
204 are always fully trusted?
205 :type always_trust: bool
206 :param passphrase: The passphrase to be used if symmetric encryption
208 :type passphrase: str
209 :param symmetric: Should we encrypt to a password?
210 :type symmetric: bool
212 :return: An object with encrypted result in the `data` field.
215 # TODO: devise a way so we don't need to "always trust".
216 return gnupg.GPG.encrypt(self, data, recipient, sign=sign,
217 always_trust=always_trust,
218 passphrase=passphrase,
220 cipher_algo='AES256')
222 def decrypt(self, data, always_trust=True, passphrase=None):
224 Decrypt data using GPG.
226 :param data: The data to be decrypted.
228 :param always_trust: Skip key validation and assume that used keys
229 are always fully trusted?
230 :type always_trust: bool
231 :param passphrase: The passphrase to be used if symmetric encryption
233 :type passphrase: str
235 :return: An object with decrypted result in the `data` field.
238 # TODO: devise a way so we don't need to "always trust".
239 return gnupg.GPG.decrypt(self, data, always_trust=always_trust,
240 passphrase=passphrase)
242 def send_keys(self, keyserver, *keyids):
244 Send keys to a keyserver
246 :param keyserver: The keyserver to send the keys to.
248 :param keyids: The key ids to send.
251 :return: A list of keys sent to server.
252 :rtype: gnupg.ListKeys
254 # TODO: write tests for this.
255 # TODO: write a SendKeys class to handle status for this.
256 result = self.result_map['list'](self)
257 gnupg.logger.debug('send_keys: %r', keyids)
258 data = gnupg._make_binary_stream("", self.encoding)
259 args = ['--keyserver', keyserver, '--send-keys']
261 self._handle_io(args, data, result, binary=True)
262 gnupg.logger.debug('send_keys result: %r', result.__dict__)
266 def encrypt_file(self, file, recipients, sign=None,
267 always_trust=False, passphrase=None,
268 armor=True, output=None, symmetric=False,
271 Encrypt the message read from the file-like object 'file'.
273 :param file: The file to be encrypted.
275 :param recipient: The address of the public key to be used.
277 :param sign: Should the encrypted content be signed?
279 :param always_trust: Skip key validation and assume that used keys
280 are always fully trusted?
281 :type always_trust: bool
282 :param passphrase: The passphrase to be used if symmetric encryption
284 :type passphrase: str
285 :param armor: Create ASCII armored output?
287 :param output: Path of file to write results in.
289 :param symmetric: Should we encrypt to a password?
290 :type symmetric: bool
291 :param cipher_algo: Algorithm to use.
292 :type cipher_algo: str
294 :return: An object with encrypted result in the `data` field.
299 args = ['--symmetric']
301 args.append('--cipher-algo %s' % cipher_algo)
304 if not _is_sequence(recipients):
305 recipients = (recipients,)
306 for recipient in recipients:
307 args.append('--recipient "%s"' % recipient)
308 if armor: # create ascii-armored output - set to False for binary
309 args.append('--armor')
310 if output: # write the output to a file with the specified name
311 if os.path.exists(output):
312 os.remove(output) # to avoid overwrite confirmation message
313 args.append('--output "%s"' % output)
315 args.append('--sign --default-key "%s"' % sign)
317 args.append("--always-trust")
318 result = self.result_map['crypt'](self)
319 self._handle_io(args, file, result, passphrase=passphrase, binary=True)
320 logger.debug('encrypt result: %r', result.data)
323 def list_packets(self, data):
325 List the sequence of packets.
327 :param data: The data to extract packets from.
330 :return: An object with packet info.
333 args = ["--list-packets"]
334 result = self.result_map['list-packets'](self)
337 _make_binary_stream(data, self.encoding),
342 def encrypted_to(self, data):
344 Return the key to which data is encrypted to.
346 :param data: The data to be examined.
349 :return: The fingerprint of the key to which data is encrypted to.
352 # TODO: make this support multiple keys.
353 result = self.list_packets(data)
356 "Content is not encrypted to a GnuPG key!")
358 return self.find_key_by_keyid(result.key)
360 return self.find_key_by_subkey(result.key)
362 def is_encrypted_sym(self, data):
364 Say whether some chunk of data is encrypted to a symmetric key.
366 :param data: The data to be examined.
369 :return: Whether data is encrypted to a symmetric key.
372 result = self.list_packets(data)
373 return bool(result.need_passphrase_sym)
375 def is_encrypted_asym(self, data):
377 Say whether some chunk of data is encrypted to a private key.
379 :param data: The data to be examined.
382 :return: Whether data is encrypted to a private key.
385 result = self.list_packets(data)
386 return bool(result.key)
388 def is_encrypted(self, data):
390 Say whether some chunk of data is encrypted to a key.
392 :param data: The data to be examined.
395 :return: Whether data is encrypted to a key.
398 return self.is_encrypted_asym(data) or self.is_encrypted_sym(data)