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 gnupg.GPG.__init__(self, gnupghome=gnupghome, gpgbinary=gpgbinary,
114 verbose=verbose, use_agent=use_agent,
115 keyring=keyring, options=options)
116 self.result_map['list-packets'] = ListPackets
118 def find_key_by_email(self, email, secret=False):
120 Find user's key based on their email.
122 :param email: Email address of key being searched for.
124 :param secret: Should we search for a secret key?
127 :return: The fingerprint of the found key.
130 for key in self.list_keys(secret=secret):
131 for uid in key['uids']:
132 if re.search(email, uid):
134 raise LookupError("GnuPG public key for email %s not found!" % email)
136 def find_key_by_subkey(self, subkey, secret=False):
138 Find user's key based on a subkey fingerprint.
140 :param email: Subkey fingerprint of the key being searched for.
142 :param secret: Should we search for a secret key?
145 :return: The fingerprint of the found key.
148 for key in self.list_keys(secret=secret):
149 for sub in key['subkeys']:
153 "GnuPG public key for subkey %s not found!" % subkey)
155 def find_key_by_keyid(self, keyid, secret=False):
157 Find user's key based on the key ID.
159 :param email: The key ID of the key being searched for.
161 :param secret: Should we search for a secret key?
164 :return: The fingerprint of the found key.
167 for key in self.list_keys(secret=secret):
168 if keyid == key['keyid']:
171 "GnuPG public key for keyid %s not found!" % keyid)
173 def find_key_by_fingerprint(self, fingerprint, secret=False):
175 Find user's key based on the key fingerprint.
177 :param email: The fingerprint of the key being searched for.
179 :param secret: Should we search for a secret key?
182 :return: The fingerprint of the found key.
185 for key in self.list_keys(secret=secret):
186 if fingerprint == key['fingerprint']:
189 "GnuPG public key for fingerprint %s not found!" % fingerprint)
191 def encrypt(self, data, recipient, sign=None, always_trust=True,
192 passphrase=None, symmetric=False):
194 Encrypt data using GPG.
196 :param data: The data to be encrypted.
198 :param recipient: The address of the public key to be used.
200 :param sign: Should the encrypted content be signed?
202 :param always_trust: Skip key validation and assume that used keys
203 are always fully trusted?
204 :type always_trust: bool
205 :param passphrase: The passphrase to be used if symmetric encryption
207 :type passphrase: str
208 :param symmetric: Should we encrypt to a password?
209 :type symmetric: bool
211 :return: An object with encrypted result in the `data` field.
214 # TODO: devise a way so we don't need to "always trust".
215 return gnupg.GPG.encrypt(self, data, recipient, sign=sign,
216 always_trust=always_trust,
217 passphrase=passphrase,
219 cipher_algo='AES256')
221 def decrypt(self, data, always_trust=True, passphrase=None):
223 Decrypt data using GPG.
225 :param data: The data to be decrypted.
227 :param always_trust: Skip key validation and assume that used keys
228 are always fully trusted?
229 :type always_trust: bool
230 :param passphrase: The passphrase to be used if symmetric encryption
232 :type passphrase: str
234 :return: An object with decrypted result in the `data` field.
237 # TODO: devise a way so we don't need to "always trust".
238 return gnupg.GPG.decrypt(self, data, always_trust=always_trust,
239 passphrase=passphrase)
241 def send_keys(self, keyserver, *keyids):
243 Send keys to a keyserver
245 :param keyserver: The keyserver to send the keys to.
247 :param keyids: The key ids to send.
250 :return: A list of keys sent to server.
251 :rtype: gnupg.ListKeys
253 # TODO: write tests for this.
254 # TODO: write a SendKeys class to handle status for this.
255 result = self.result_map['list'](self)
256 gnupg.logger.debug('send_keys: %r', keyids)
257 data = gnupg._make_binary_stream("", self.encoding)
258 args = ['--keyserver', keyserver, '--send-keys']
260 self._handle_io(args, data, result, binary=True)
261 gnupg.logger.debug('send_keys result: %r', result.__dict__)
265 def encrypt_file(self, file, recipients, sign=None,
266 always_trust=False, passphrase=None,
267 armor=True, output=None, symmetric=False,
270 Encrypt the message read from the file-like object 'file'.
272 :param file: The file to be encrypted.
274 :param recipient: The address of the public key to be used.
276 :param sign: Should the encrypted content be signed?
278 :param always_trust: Skip key validation and assume that used keys
279 are always fully trusted?
280 :type always_trust: bool
281 :param passphrase: The passphrase to be used if symmetric encryption
283 :type passphrase: str
284 :param armor: Create ASCII armored output?
286 :param output: Path of file to write results in.
288 :param symmetric: Should we encrypt to a password?
289 :type symmetric: bool
290 :param cipher_algo: Algorithm to use.
291 :type cipher_algo: str
293 :return: An object with encrypted result in the `data` field.
298 args = ['--symmetric']
300 args.append('--cipher-algo %s' % cipher_algo)
303 if not _is_sequence(recipients):
304 recipients = (recipients,)
305 for recipient in recipients:
306 args.append('--recipient "%s"' % recipient)
307 if armor: # create ascii-armored output - set to False for binary
308 args.append('--armor')
309 if output: # write the output to a file with the specified name
310 if os.path.exists(output):
311 os.remove(output) # to avoid overwrite confirmation message
312 args.append('--output "%s"' % output)
314 args.append('--sign --default-key "%s"' % sign)
316 args.append("--always-trust")
317 result = self.result_map['crypt'](self)
318 self._handle_io(args, file, result, passphrase=passphrase, binary=True)
319 logger.debug('encrypt result: %r', result.data)
322 def list_packets(self, data):
324 List the sequence of packets.
326 :param data: The data to extract packets from.
329 :return: An object with packet info.
332 args = ["--list-packets"]
333 result = self.result_map['list-packets'](self)
336 _make_binary_stream(data, self.encoding),
341 def encrypted_to(self, data):
343 Return the key to which data is encrypted to.
345 :param data: The data to be examined.
348 :return: The fingerprint of the key to which data is encrypted to.
351 # TODO: make this support multiple keys.
352 result = self.list_packets(data)
355 "Content is not encrypted to a GnuPG key!")
357 return self.find_key_by_keyid(result.key)
359 return self.find_key_by_subkey(result.key)
361 def is_encrypted_sym(self, data):
363 Say whether some chunk of data is encrypted to a symmetric key.
365 :param data: The data to be examined.
368 :return: Whether data is encrypted to a symmetric key.
371 result = self.list_packets(data)
372 return bool(result.need_passphrase_sym)
374 def is_encrypted_asym(self, data):
376 Say whether some chunk of data is encrypted to a private key.
378 :param data: The data to be examined.
381 :return: Whether data is encrypted to a private key.
384 result = self.list_packets(data)
385 return bool(result.key)
387 def is_encrypted(self, data):
389 Say whether some chunk of data is encrypted to a key.
391 :param data: The data to be examined.
394 :return: Whether data is encrypted to a key.
397 return self.is_encrypted_asym(data) or self.is_encrypted_sym(data)