def test_message_sign(self): """ Test if message is signed with sender key. """ # mock the key fetching self.km._fetch_keys_from_server = Mock( return_value=fail(errors.KeyNotFound())) recipient = User('*****@*****.**', 'gateway.leap.se', self.proto, ADDRESS) self.outgoing_mail = OutgoingMail( self.fromAddr, self.km, self.opts.cert, self.opts.key, self.opts.hostname, self.opts.port) def check_signed(res): message, _ = res self.assertTrue('Content-Type' in message) self.assertEqual('multipart/signed', message.get_content_type()) self.assertEqual('application/pgp-signature', message.get_param('protocol')) self.assertEqual('pgp-sha512', message.get_param('micalg')) # assert content of message body = (message.get_payload(0) .get_payload(0) .get_payload(decode=True)) self.assertEqual(self.expected_body, body) # assert content of signature self.assertTrue( message.get_payload(1).get_payload().startswith( '-----BEGIN PGP SIGNATURE-----\n'), 'Message does not start with signature header.') self.assertTrue( message.get_payload(1).get_payload().endswith( '-----END PGP SIGNATURE-----\n'), 'Message does not end with signature footer.') return message def verify(message): # replace EOL before verifying (according to rfc3156) fp = StringIO() g = RFC3156CompliantGenerator( fp, mangle_from_=False, maxheaderlen=76) g.flatten(message.get_payload(0)) signed_text = re.sub('\r?\n', '\r\n', fp.getvalue()) def assert_verify(key): self.assertTrue(ADDRESS_2 in key.address, 'Signature could not be verified.') d = self.km.verify( signed_text, ADDRESS_2, detached_sig=message.get_payload(1).get_payload()) d.addCallback(assert_verify) return d d = self.outgoing_mail._maybe_encrypt_and_sign(self.raw, recipient) d.addCallback(check_signed) d.addCallback(verify) return d
def put_raw_key(self, key, address, validation=ValidationLevels.Weak_Chain): """ Put raw key bound to address in local storage. :param key: The key to be stored :type key: str :param address: address for which this key will be active :type address: str :param validation: validation level for this key (default: 'Weak_Chain') :type validation: ValidationLevels :return: A Deferred which fires when the key is in the storage, or which fails with KeyAddressMismatch if address doesn't match any uid on the key or fails with KeyNotFound if no OpenPGP material was found in key or fails with KeyNotValidUpdate if a key with the same uid exists and the new one is not a valid update for it. :rtype: Deferred :raise UnsupportedKeyTypeError: if invalid key type """ pubkey, privkey = self._openpgp.parse_key(key, address) if pubkey is None: return defer.fail(keymanager_errors.KeyNotFound(key)) pubkey.validation = validation d = self.put_key(pubkey) if privkey is not None: d.addCallback(lambda _: self.put_key(privkey)) return d
def fetch_key(self, address, uri, validation=ValidationLevels.Weak_Chain): """ Fetch a public key bound to address from the network and put it in local storage. :param address: The email address of the key. :type address: str :param uri: The URI of the key. :type uri: str :param validation: validation level for this key (default: 'Weak_Chain') :type validation: ValidationLevels :return: A Deferred which fires when the key is in the storage, or which fails with KeyNotFound: if not valid key on uri or fails with KeyAddressMismatch if address doesn't match any uid on the key or fails with KeyNotValidUpdate if a key with the same uid exists and the new one is not a valid update for it. :rtype: Deferred :raise UnsupportedKeyTypeError: if invalid key type """ self.log.info('Fetch key for %s from %s' % (address, uri)) key_content = yield self._get_with_combined_ca_bundle(uri) # XXX parse binary keys pubkey, _ = self._openpgp.parse_key(key_content, address) if pubkey is None: raise keymanager_errors.KeyNotFound(uri) pubkey.validation = validation yield self.put_key(pubkey)
def fetch_key_fingerprint(self, address, fingerprint): """ Fetch a key from the key servers by fingerprint. It will replace any key assigned to the address in the keyring and have validation level Fingerprint. :param address: The address bound to the key. :type address: str :param fingerprint: The fingerprint of the key to fetch. :type fingerprint: str :return: A Deferred which fires with an EncryptionKey fetched, or which fails with KeyNotFound if no key was found in the keyserver for this fingerprint. :rtype: Deferred """ key_data = yield self._nicknym.fetch_key_with_fingerprint(fingerprint) key, _ = self._openpgp.parse_key(key_data, address) key.validation = ValidationLevels.Fingerprint if key.fingerprint != fingerprint: raise keymanager_errors.KeyNotFound("Got wrong fingerprint") try: old_key = yield self._openpgp.get_key(address) if old_key.fingerprint == key.fingerprint: key.last_audited_at = old_key.last_audited_at key.encr_used = old_key.encr_used key.sign_used = old_key.sign_used except keymanager_errors.KeyNotFound: pass yield self._openpgp.put_key(key) defer.returnValue(key)
def test_missing_key_rejects_address(self): """ Test if server rejects to send unencrypted when 'encrypted_only' is True. """ # remove key from key manager pubkey = yield self.km.get_key(ADDRESS) pgp = openpgp.OpenPGPScheme(self._soledad, gpgbinary=self.gpg_binary_path) yield pgp.delete_key(pubkey) # mock the key fetching self.km._fetch_keys_from_server = Mock( return_value=fail(errors.KeyNotFound())) user = TEST_USER proto = getSMTPFactory({user: None}, {user: self.km}, {user: None}, encrypted_only=True) transport = proto_helpers.StringTransport() proto.makeConnection(transport) yield self.getReply(self.EMAIL_DATA[0] + '\r\n', proto, transport) yield self.getReply(self.EMAIL_DATA[1] + '\r\n', proto, transport) reply = yield self.getReply(self.EMAIL_DATA[2] + '\r\n', proto, transport) # ensure the address was rejected self.assertEqual( '550 Cannot receive for specified address\r\n', reply, 'Address should have been rejected with appropriate message.') proto.setTimeout(None)
def test_missing_key_accepts_address(self): """ Test if server accepts to send unencrypted when 'encrypted_only' is False. """ # remove key from key manager pubkey = yield self.km.get_key(ADDRESS) pgp = openpgp.OpenPGPScheme(self._soledad, gpgbinary=self.gpg_binary_path) yield pgp.delete_key(pubkey) # mock the key fetching self.km._fetch_keys_from_server_and_store_local = Mock( return_value=fail(errors.KeyNotFound())) user = TEST_USER proto = getSMTPFactory({user: OutgoingMail(user, self.km)}, {user: None}) transport = proto_helpers.StringTransport() proto.makeConnection(transport) yield self.getReply(self.EMAIL_DATA[0] + '\r\n', proto, transport) yield self.getReply(self.EMAIL_DATA[1] + '\r\n', proto, transport) reply = yield self.getReply(self.EMAIL_DATA[2] + '\r\n', proto, transport) # ensure the address was accepted self.assertEqual( '250 Recipient address accepted\r\n', reply, 'Address should have been accepted with appropriate message.') proto.setTimeout(None)
def delete_key(docs): if len(docs) == 0: raise errors.KeyNotFound(key) elif len(docs) > 1: self.log.warn('There is more than one key for fingerprint %s' % key.fingerprint) has_deleted = False deferreds = [] for doc in docs: if doc.content['fingerprint'] == key.fingerprint: d = self._soledad.delete_doc(doc) deferreds.append(d) has_deleted = True if not has_deleted: raise errors.KeyNotFound(key) return defer.gatherResults(deferreds)
def build_key((keydoc, activedoc)): if keydoc is None: raise errors.KeyNotFound(address) leap_assert( address in keydoc.content[KEY_UIDS_KEY], 'Wrong address in key %s. Expected %s, found %s.' % (keydoc.content[KEY_FINGERPRINT_KEY], address, keydoc.content[KEY_UIDS_KEY])) key = build_key_from_dict(keydoc.content, activedoc.content) key._gpgbinary = self._gpgbinary return key
def _get_key_from_nicknym(self, address): """ Send a GET request to C{uri} containing C{data}. :param address: The URI of the request. :type address: str :return: A deferred that will be fired with GET content as json (dict) :rtype: Deferred """ try: uri = self._nickserver_uri + '?address=' + address content = yield self._fetch_and_handle_404_from_nicknym( uri, address) json_content = json.loads(content) except keymanager_errors.KeyNotFound: raise except IOError as e: self.log.warn("HTTP error retrieving key: %r" % (e, )) self.log.warn("%s" % (content, )) raise keymanager_errors.KeyNotFound(e.message), \ None, sys.exc_info()[2] except ValueError as v: self.log.warn("Invalid JSON data from key: %s" % (uri, )) raise keymanager_errors.KeyNotFound(v.message + ' - ' + uri), \ None, sys.exc_info()[2] except Exception as e: self.log.warn("Error retrieving key: %r" % (e, )) raise keymanager_errors.KeyNotFound(e.message), \ None, sys.exc_info()[2] # Responses are now text/plain, although it's json anyway, but # this will fail when it shouldn't # leap_assert( # res.headers['content-type'].startswith('application/json'), # 'Content-type is not JSON.') defer.returnValue(json_content)
def _get_with_combined_ca_bundle(self, uri, data=None): """ Send a GET request to C{uri} containing C{data}. Instead of using the ca_cert provided on construction time, this version also uses the default certificates shipped with leap.common :param uri: The URI of the request. :type uri: str :param data: The body of the request. :type data: dict, str or file :return: A deferred that will be fired with the GET response :rtype: Deferred """ try: content = yield self._async_client.request(str(uri), 'GET') except Exception as e: self.log.warn("There was a problem fetching key: %s" % (e, )) raise keymanager_errors.KeyNotFound(uri) if not content: raise keymanager_errors.KeyNotFound(uri) defer.returnValue(content)
def test_non_existing_key_from_nicknym_is_relayed(self): """ Test if key search requests throws KeyNotFound, the same error is raised. """ km = self._key_manager(url=NICKSERVER_URI) key_not_found_exception = errors.KeyNotFound('some message') km._nicknym._async_client_pinned.request = mock.Mock( side_effect=key_not_found_exception) def assert_key_not_found_raised(error): self.assertEqual(error.value, key_not_found_exception) d = km._nicknym.fetch_key_with_address(INVALID_MAIL_ADDRESS) d.addErrback(assert_key_not_found_raised)
def put_raw_key(self, key, address, validation=ValidationLevels.Weak_Chain): """ Put raw key bound to address in local storage. :param key: The key to be stored :type key: str :param address: address for which this key will be active :type address: str :param validation: validation level for this key (default: 'Weak_Chain') :type validation: ValidationLevels :return: A Deferred which fires when the key is in the storage, or which fails with KeyAddressMismatch if address doesn't match any uid on the key or fails with KeyNotFound if no OpenPGP material was found in key or fails with KeyNotValidUpdate if a key with the same uid exists and the new one is not a valid update for it. :rtype: Deferred :raise UnsupportedKeyTypeError: if invalid key type """ pubkey, privkey = self._openpgp.parse_key(key, address) if pubkey is None: raise keymanager_errors.KeyNotFound(key) if address == self._address and not privkey: try: existing = yield self.get_key(address, fetch_remote=False) except KeyNotFound: existing = None if (existing is None or pubkey.fingerprint != existing.fingerprint): raise keymanager_errors.KeyNotValidUpgrade( "Cannot update your %s key without the private part" % (address, )) pubkey.validation = validation yield self.put_key(pubkey) if privkey is not None: yield self.put_key(privkey) if address == self._address: yield self.send_key()
def decrypt(keys): pubkey, privkey = keys decrypted, signed = yield self._openpgp.decrypt( data, privkey, passphrase=passphrase, verify=pubkey) if pubkey is None: signature = keymanager_errors.KeyNotFound(verify) elif signed: signature = pubkey if not pubkey.sign_used: pubkey.sign_used = True yield self._openpgp.put_key(pubkey) defer.returnValue((decrypted, signature)) else: signature = keymanager_errors.InvalidSignature( 'Failed to verify signature with key %s' % (pubkey.fingerprint, )) defer.returnValue((decrypted, signature))