Exemplo n.º 1
0
 def encrypt(self, recipient=None):
     import duckbill.config
     if recipient is None:
         recipient = duckbill.config.GNUPG_RECIPIENT
     gpg = GnuPG()
     data = "|".join([self.owner, self.number, self.expire.toSQL()])
     self._cipher = gpg.encrypt_string(data, [recipient])
     return self._cipher
Exemplo n.º 2
0
 def encrypt(self, recipient=None):
     import duckbill.config
     if recipient is None:
         recipient = duckbill.config.GNUPG_RECIPIENT
     gpg = GnuPG()
     data = "|".join([self.owner, self.number, self.expire.toSQL()])
     self._cipher = gpg.encrypt_string(data, [recipient])
     return self._cipher
Exemplo n.º 3
0
def encrypt_payload( payload, gpg_to_cmdline, check_nested = True ):

	raw_payload = payload.get_payload(decode=True)
	if check_nested and "-----BEGIN PGP MESSAGE-----" in raw_payload and "-----END PGP MESSAGE-----" in raw_payload:
		if verbose:
			log("Message is already pgp encrypted. No nested encryption needed.")
		return payload

	# No check is needed for cfg['gpg']['keyhome'] as this is already done in method gpg_encrypt
	gpg = GnuPG.GPGEncryptor( cfg['gpg']['keyhome'], gpg_to_cmdline, payload.get_content_charset() )
	gpg.update( raw_payload )
	encrypted_data, returncode = gpg.encrypt()
	if verbose:
		log("Return code from encryption=%d (0 indicates success)." % returncode)
	if returncode != 0:
		log("Encrytion failed with return code %d. Encryption aborted." % returncode)
		return payload

	payload.set_payload( encrypted_data )
	isAttachment = payload.get_param( 'attachment', None, 'Content-Disposition' ) is not None

	if isAttachment:
		filename = payload.get_filename()
		if filename:
			pgpFilename = filename + ".pgp"
			if not (payload.get('Content-Disposition') is None):
				payload.set_param( 'filename', pgpFilename, 'Content-Disposition' )
			if not (payload.get('Content-Type') is None) and not (payload.get_param( 'name' ) is None):
				payload.set_param( 'name', pgpFilename )
	if not (payload.get('Content-Transfer-Encoding') is None):
		payload.replace_header( 'Content-Transfer-Encoding', "7bit" )

	return payload
Exemplo n.º 4
0
def encrypt_payload(payload, gpg_to_cmdline):
    raw_payload = payload.get_payload(decode=True)
    if "-----BEGIN PGP MESSAGE-----" in raw_payload and "-----END PGP MESSAGE-----" in raw_payload:
        return payload
    gpg = GnuPG.GPGEncryptor(cfg['gpg']['keyhome'], gpg_to_cmdline,
                             payload.get_content_charset())
    gpg.update(raw_payload)
    payload.set_payload(gpg.encrypt())

    isAttachment = payload.get_param('attachment', None,
                                     'Content-Disposition') is not None

    if isAttachment:
        filename = payload.get_filename()

        if filename:
            pgpFilename = filename + ".pgp"

            if payload.get('Content-Disposition') is not None:
                payload.set_param('filename', pgpFilename,
                                  'Content-Disposition')
            if payload.get('Content-Type') is not None:
                if payload.get_param('name') is not None:
                    payload.set_param('name', pgpFilename)

    if payload.get('Content-Transfer-Encoding') is not None:
        payload.replace_header('Content-Transfer-Encoding', "7bit")

    return payload
Exemplo n.º 5
0
def gpg_decrypt( raw_message, recipients ):

	gpg_to = list()
	ungpg_to = list()

	# This is needed to avoid encryption if decryption is set to keymap only,
	# private key is present but not in keymap.
	noenc_to = list()

	if not get_bool_from_cfg('gpg', 'keyhome'):
		log("No valid entry for gpg keyhome. Decryption aborted.")
		return recipients

	keys = GnuPG.private_keys( cfg['gpg']['keyhome'] )

	if get_bool_from_cfg('default', 'dec_regex'):
		dec_regex = cfg['default']['dec_regex']
	else:
		dec_regex = None

	for fingerprint in keys:
		keys[fingerprint] = sanitize_case_sense(keys[fingerprint])

	for to in recipients:
		if to in keys.values() and not get_bool_from_cfg('default', 'dec_keymap_only', 'yes'):
			gpg_to.append(to)
		# Is this recipient defined in regex for default decryption?
		elif not (dec_regex is None) and not (re.match(dec_regex, to) is None):
			log("Using default decrytion defined in dec_regex for recipient '%s'" % to)
			gpg_to.append(to)
		elif get_bool_from_cfg('dec_keymap', to):
			log("Decrypt keymap has key '%s'" % cfg['dec_keymap'][to] )
			# Check we've got a matching key! If not, decline to attempt decryption. The key is checked for safty reasons.
			if not cfg['dec_keymap'][to] in keys:
				log("Key '%s' in decryption keymap not found in keyring for email address '%s'. Won't decrypt." % (cfg['dec_keymap'][to], to))
				# Avoid unwanted encryption if set
				if to in keys.values() and get_bool_from_cfg('default', 'failsave_dec', 'yes'):
					noenc_to.append(to)
				else:
					ungpg_to.append(to)
			else:
				gpg_to.append(to)
		else:
			if verbose:
				log("Recipient (%s) not in PGP domain list for decrypting." % to)
			# Avoid unwanted encryption if set
			if to in keys.values() and get_bool_from_cfg('default', 'failsave_dec', 'yes'):
				noenc_to.append(to)
			else:
				ungpg_to.append(to)

	if gpg_to != list():
		send_msg( gpg_decrypt_all_payloads( raw_message ).as_string(), gpg_to )

	if noenc_to != list():
		log("Do not try to encrypt mails for: %s" % ', '.join( noenc_to ))
		send_msg(raw_message.as_string(), noenc_to)

	return ungpg_to
Exemplo n.º 6
0
def gpg_decrypt( raw_message, recipients ):

	gpg_to = list()
	ungpg_to = list()

	# This is needed to avoid encryption if decryption is set to keymap only,
	# private key is present but not in keymap.
	noenc_to = list()

	if not get_bool_from_cfg('gpg', 'keyhome'):
		log("No valid entry for gpg keyhome. Decryption aborted.")
		return recipients

	keys = GnuPG.private_keys( cfg['gpg']['keyhome'] )

	if get_bool_from_cfg('default', 'dec_regex'):
		dec_regex = cfg['default']['dec_regex']
	else:
		dec_regex = None

	for fingerprint in keys:
		keys[fingerprint] = sanitize_case_sense(keys[fingerprint])

	for to in recipients:
		if to in keys.values() and not get_bool_from_cfg('default', 'dec_keymap_only', 'yes'):
			gpg_to.append(to)
		# Is this recipient defined in regex for default decryption?
		elif not (dec_regex is None) and not (re.match(dec_regex, to) is None):
			log("Using default decrytion defined in dec_regex for recipient '%s'" % to)
			gpg_to.append(to)
		elif get_bool_from_cfg('dec_keymap', to):
			log("Decrypt keymap has key '%s'" % cfg['dec_keymap'][to] )
			# Check we've got a matching key! If not, decline to attempt decryption. The key is checked for safty reasons.
			if not cfg['dec_keymap'][to] in keys:
				log("Key '%s' in decryption keymap not found in keyring for email address '%s'. Won't decrypt." % (cfg['dec_keymap'][to], to))
				# Avoid unwanted encryption if set
				if to in keys.values() and get_bool_from_cfg('default', 'failsave_dec', 'yes'):
					noenc_to.append(to)
				else:
					ungpg_to.append(to)
			else:
				gpg_to.append(to)
		else:
			if verbose:
				log("Recipient (%s) not in PGP domain list for decrypting." % to)
			# Avoid unwanted encryption if set
			if to in keys.values() and get_bool_from_cfg('default', 'failsave_dec', 'yes'):
				noenc_to.append(to)
			else:
				ungpg_to.append(to)

	if gpg_to != list():
		send_msg( gpg_decrypt_all_payloads( raw_message ).as_string(), gpg_to )

	if noenc_to != list():
		log("Do not try to encrypt mails for: %s" % ', '.join( noenc_to ))
		send_msg(raw_message.as_string(), noenc_to)

	return ungpg_to
Exemplo n.º 7
0
def main():
    GnuPG.main()  # initialises the GnuPG engine

    print("Do you wish to (e)ncrypt a message or (d)ecrypt a file?")
    choice = input("> ")

    if choice.lower() == "e":
        print("Please enter the Keybase username of the recipient")
        username = input(">")

        print("Please enter the email of the recipient")
        email = input(">")

        print("Please enter the path to the file you wish to encrypt and sign")
        path_to_file = input(">")

        print("%s %s %s" %
              (username, email, os.path.realpath(path_to_file)))  # DEBUG
        GnuPG.import_key(username)
        GnuPG.encrypt_message(path_to_file, email)
        file_size = os.path.getsize(path_to_file + '.gpg')

        gaps = getGaps(file_size)
        print(gaps)

        print(
            "Please enter the directory that you wish to place the outputted files (leave blank for this dir)"
        )
        path_to_output = input(">")
        if path_to_output == "":
            path_to_output = "./"

        GapFillerStego.place(path_to_file + '.gpg', gaps, path_to_output)

    elif choice.lower() == "d":
        print(
            "Please enter the path to the file you wish to check for encrypted content"
        )
        path_to_file = input(">")
        print(
            "Please enter the directory that you wish to place the outputted file (leave blank for this dir)"
        )
        path_to_output = input(">")
        if path_to_output == "":
            path_to_output = "./"

        print("%s" % (os.path.realpath(path_to_file)))
        ciphertext_path = GapFillerStego.retrieve(path_to_file, path_to_output)
        if ciphertext_path is not None:
            GnuPG.decrypt_message(ciphertext_path)
    elif choice.lower() == "exit":
        exit(0)
    else:
        print("Invalid input, please try again")
        main()
Exemplo n.º 8
0
def encrypt_payload( payload, gpg_to_cmdline ):
	raw_payload = payload.get_payload(decode=True)
	if "-----BEGIN PGP MESSAGE-----" in raw_payload and "-----END PGP MESSAGE-----" in raw_payload:
		return payload
	gpg = GnuPG.GPGEncryptor( cfg['gpg']['keyhome'], gpg_to_cmdline, payload.get_content_charset() )
	gpg.update( raw_payload )
	payload.set_payload( gpg.encrypt() )
	if payload['Content-Disposition']:
		payload.replace_header( 'Content-Disposition', re.sub(r'filename="([^"]+)"', r'filename="\1.pgp"', payload['Content-Disposition']) )
	if payload['Content-Type']:
		payload.replace_header( 'Content-Type', re.sub(r'name="([^"]+)"', r'name="\1.pgp"', payload['Content-Type']) )
		if 'name="' in payload['Content-Type']:
			payload.replace_header( 'Content-Type', re.sub(r'^[a-z/]+;', r'application/octet-stream;', payload['Content-Type']) )
			payload.set_payload( "\n".join( filter( lambda x:re.search(r'^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$',x), payload.get_payload().split("\n") ) ) )
	return payload
Exemplo n.º 9
0
def decrypt_payload( payload ):

	gpg = GnuPG.GPGDecryptor( cfg['gpg']['keyhome'] )
	gpg.update( payload )
	decrypted_data, returncode = gpg.decrypt()
	if verbose:
		log("Return code from decryption=%d (0 indicates success)." % returncode)
	if returncode != 0:
		log("Decrytion failed with return code %d. Decryption aborted." % returncode)
		return payload, False

	# Decryption always generate a new message
	decrypted_msg = email.message_from_string(decrypted_data)

	return decrypted_msg, True
Exemplo n.º 10
0
def main():
    GnuPG.main()  # initialises the GnuPG engine
    gaps_placed = 0
    gaps_retrieved = 0

    print("Please enter the Keybase username of the recipient")
    username = input(">")

    if username == "auto1":  # Use this to automate multiple runs and reduce the amount of typing
        username = ""
        email = ""
        path_to_file = "out.txt"
        path_to_output = ""
    else:
        print("Please enter the email of the recipient")
        email = input(">")

        print("Please enter the path to the file you wish to encrypt and sign")
        path_to_file = input(">")

        print(
            "Please enter the directory that you wish to place the outputted files"
        )
        path_to_output = input(">")

    print("%s %s %s" %
          (username, email, os.path.realpath(path_to_file)))  # DEBUG
    GnuPG.import_key(username)
    GnuPG.encrypt_message(path_to_file, email)
    file_size = os.path.getsize(path_to_file + '.gpg')

    gaps = getGaps(file_size)
    print(gaps)
    gaps_placed = len(gaps)

    for x in gaps:
        GapFillerStego.place(path_to_file + '.gpg', [x], path_to_output)

    print(
        "Please enter the directory that you wish to place the outputted files"
    )
    msg_output = input(">")

    for root, dirs, files in os.walk(path_to_output):
        for name in files:  # for each file in path
            success = GapFillerStego.retrieve(os.path.join(root, name),
                                              os.path.realpath(msg_output))
            if success is not None:
                gaps_retrieved = gaps_retrieved + 1

    print("Gaps Placed - %s, Gaps Retrieved - %s, Percentage Recovered - %s" %
          (gaps_placed, gaps_retrieved,
           ((gaps_retrieved / gaps_placed) * 100)))
Exemplo n.º 11
0
 def decrypt(self, passphrase):
     assert self.private.encrypted, "already decrypted"
     gpg = GnuPG()
     data = gpg.decrypt_string(self._cipher, passphrase)
     self.owner, self.number, self.expire = data.split("|")
     self.private.encrypted = False
Exemplo n.º 12
0
    cursor = connection.cursor()

    # import keys
    cursor.execute(
        "SELECT publickey, id, email FROM gpgmw_keys WHERE status = 0 AND confirm = '' LIMIT 100"
    )
    result_set = cursor.fetchall()

    for row in result_set:
        # delete any other public keys associated with this confirmed email address
        cursor.execute("DELETE FROM gpgmw_keys WHERE email = %s AND id != %s",
                       (
                           row[2],
                           row[1],
                       ))
        GnuPG.delete_key(cfg['gpg']['keyhome'], row[2])
        appendLog('Deleted key for <' + row[2] + '> via import request')

        if row[0].strip(
        ):  # we have this so that user can submit blank key to remove any encryption
            if GnuPG.confirm_key(row[0], row[2]):
                GnuPG.add_key(cfg['gpg']['keyhome'],
                              row[0])  # import the key to gpg
                cursor.execute(
                    "UPDATE gpgmw_keys SET status = 1 WHERE id = %s",
                    (row[1], ))  # mark key as accepted
                appendLog('Imported key from <' + row[2] + '>')
                if cfg['cron'].has_key(
                        'send_email') and cfg['cron']['send_email'] == 'yes':
                    send_msg("PGP key registration successful",
                             "registrationSuccess.md", row[2])
Exemplo n.º 13
0
	cfg[sect] = dict()
	for (name, value) in _cfg.items(sect):
		cfg[sect][name] = value

if cfg.has_key('database') and cfg['database'].has_key('enabled') and cfg['database']['enabled'] == 'yes' and cfg['database'].has_key('name') and cfg['database'].has_key('host') and cfg['database'].has_key('username') and cfg['database'].has_key('password'):
	connection = MySQLdb.connect(host = cfg['database']['host'], user = cfg['database']['username'], passwd = cfg['database']['password'], db = cfg['database']['name'], port = 3306)
	cursor = connection.cursor()

	# import keys
	cursor.execute("SELECT publickey, id, email FROM gpgmw_keys WHERE status = 0 AND confirm = '' LIMIT 100")
	result_set = cursor.fetchall()

	for row in result_set:
		# delete any other public keys associated with this confirmed email address
		cursor.execute("DELETE FROM gpgmw_keys WHERE email = %s AND id != %s", (row[2], row[1],))
		GnuPG.delete_key(cfg['gpg']['keyhome'], row[2])
		appendLog('Deleted key for <' + row[2] + '> via import request')

		if row[0].strip(): # we have this so that user can submit blank key to remove any encryption
			if GnuPG.confirm_key(row[0], row[2]):
				GnuPG.add_key(cfg['gpg']['keyhome'], row[0]) # import the key to gpg
				cursor.execute("UPDATE gpgmw_keys SET status = 1 WHERE id = %s", (row[1],)) # mark key as accepted
				appendLog('Imported key from <' + row[2] + '>')
				if cfg['cron'].has_key('send_email') and cfg['cron']['send_email'] == 'yes':
					send_msg( "PGP key registration successful", "registrationSuccess.md", row[2] )
			else:
				cursor.execute("DELETE FROM gpgmw_keys WHERE id = %s", (row[1],)) # delete key
				appendLog('Import confirmation failed for <' + row[2] + '>')
				if cfg['cron'].has_key('send_email') and cfg['cron']['send_email'] == 'yes':
					send_msg( "PGP key registration failed", "registrationError.md", row[2] )
		else:
Exemplo n.º 14
0
        msg = MIMEMultipart("alternative")
        msg["From"] = cfg['mailregister']['register_email']
        msg["To"] = from_addr
        msg["Subject"] = "S/MIME certificate registration succeeded"

        msg.attach(MIMEText(success_msg, 'plain'))
        msg.attach(MIMEText(markdown.markdown(success_msg), 'html'))

        send_msg(msg, cfg['mailregister']['register_email'], [from_addr])

        log("S/MIME Registration succeeded")
    elif sign_type == 'pgp':
        # send POST to gpg-mailgate webpanel
        sig = sign_part

        GnuPG.delete_key(cfg['gpg']['keyhome'], from_addr)
        log('Deleted key for <%s> via import request' % from_addr)

        if from_addr.strip(
        ):  # we have this so that user can submit blank key to remove any encryption
            if not GnuPG.confirm_key(sig, from_addr):
                log("Can not verify sig for email <%s>" % from_addr)
            try:
                GnuPG.add_key(cfg['gpg']['keyhome'],
                              sig)  # import the key to gpg
                log("PGP registration success")
            except:
                log("Could not hand registration over to GPGMW. Error: %s" %
                    r.status_code)
                error_msg = file(cfg['mailregister']['mail_templates'] +
                                 "/gpgmwFailed.md").read()
Exemplo n.º 15
0
    for payload in message.get_payload():
        if type(payload.get_payload()) == list:
            encrypted_payloads.extend(encrypt_all_payloads(payload, gpg_to_cmdline))
        else:
            encrypted_payloads.append(encrypt_payload(payload, gpg_to_cmdline))
    return encrypted_payloads


def get_msg(message):
    if not message.is_multipart():
        return message.get_payload()
    return "\n\n".join([str(m) for m in message.get_payload()])


keys = GnuPG.public_keys(cfg["gpg"]["keyhome"])
gpg_to = list()
ungpg_to = list()

for to in to_addrs:
    if to in keys.values() and not (cfg["default"].has_key("keymap_only") and cfg["default"]["keymap_only"] == "yes"):
        gpg_to.append((to, to))
    elif cfg.has_key("keymap") and cfg["keymap"].has_key(to):
        log("Keymap has key '%s'" % cfg["keymap"][to])
        # Check we've got a matching key!  If not, decline to attempt encryption.
        if not keys.has_key(cfg["keymap"][to]):
            log(
                "Key '%s' in keymap not found in keyring for email address '%s'.  Won't encrypt."
                % (cfg["keymap"][to], to)
            )
            ungpg_to.append(to)
Exemplo n.º 16
0
        if raw_message['Subject']:
            out.write('Subject: ' + raw_message['Subject'] + '\n')
        if cfg['default'].has_key(
                'add_header') and cfg['default']['add_header'] == 'yes':
            out.write('X-GPG-Mailgate: Encrypted by GPG Mailgate\n')
        s.write(out, p7)
        log("Sending message from " + from_addr + " to " + str(recipients))
        raw_msg = out.read()
        send_msg(raw_msg, recipients)
    else:
        log("Unable to find valid S/MIME recipient")
        send_msg(raw_message.as_string(), recipients)
    return None


keys = GnuPG.public_keys(cfg['gpg']['keyhome'])
gpg_to = list()
ungpg_to = list()

for to in to_addrs:
    if to in keys and not (cfg['default'].has_key('keymap_only')
                           and cfg['default']['keymap_only'] == 'yes'):
        gpg_to.append((to, to))
    elif cfg.has_key('keymap') and cfg['keymap'].has_key(to):
        gpg_to.append((to, cfg['keymap'][to]))
    else:
        if verbose:
            log("Recipient (%s) not in PGP domain list." % to)
        ungpg_to.append(to)

if gpg_to == list():
Exemplo n.º 17
0
        log.write("Sending email to: <%s>\n" % '> <'.join(recipients))
        log.close()
    relay = (cfg['relay']['host'], int(cfg['relay']['port']))
    smtp = smtplib.SMTP(relay[0], relay[1])
    smtp.sendmail(from_addr, recipients, message.as_string())


def get_msg(message):
    if not message.is_multipart():
        return message.get_payload()
    return '\n\n'.join(message.get_payload())


gpg_to = list()
ungpg_to = list()
keys = GnuPG.public_keys(cfg['gpg']['keyhome'])
for to in to_addrs:
    domain = to.split('@')[1]
    if domain in cfg['default']['domains'].split(','):
        if to in keys:
            gpg_to.append((to, to))
        elif cfg.has_key('keymap') and cfg['keymap'].has_key(to):
            gpg_to.append((to, cfg['keymap'][to]))
    else:
        ungpg_to.append(to)

if gpg_to == list():
    if cfg['default'].has_key(
            'add_header') and cfg['default']['add_header'] == 'yes':
        raw_message['X-GPG-Mailgate'] = 'Not encrypted, public key not found'
    send_msg(raw_message)
Exemplo n.º 18
0
 def decrypt(self, passphrase):
     assert self.private.encrypted, "already decrypted"
     gpg = GnuPG()
     data = gpg.decrypt_string(self._cipher, passphrase)
     self.owner, self.number, self.expire = data.split("|")
     self.private.encrypted = False
Exemplo n.º 19
0
def gpg_encrypt(raw_message, recipients):

    if not get_bool_from_cfg('gpg', 'keyhome'):
        log("No valid entry for gpg keyhome. Encryption aborted.")
        return recipients

    keys = GnuPG.public_keys(cfg['gpg']['keyhome'])
    for fingerprint in keys:
        keys[fingerprint] = sanitize_case_sense(keys[fingerprint])

    gpg_to = list()
    ungpg_to = list()

    for to in recipients:

        # Check if recipient is in keymap
        if get_bool_from_cfg('enc_keymap', to):
            log("Encrypt keymap has key '%s'" % cfg['enc_keymap'][to])
            # Check we've got a matching key!
            if cfg['enc_keymap'][to] in keys:
                gpg_to.append((to, cfg['enc_keymap'][to]))
                continue
            else:
                log("Key '%s' in encrypt keymap not found in keyring for email address '%s'."
                    % (cfg['enc_keymap'][to], to))

        # Check if key in keychain is present
        if to in keys.values() and not get_bool_from_cfg(
                'default', 'enc_keymap_only', 'yes'):
            gpg_to.append((to, to))
            continue

        # Check if there is a default key for the domain
        splitted_to = to.split('@')
        if len(splitted_to) > 1:
            domain = splitted_to[1]
            if get_bool_from_cfg('enc_domain_keymap', domain):
                log("Encrypt domain keymap has key '%s'" %
                    cfg['enc_dec_keymap'][domain])
                # Check we've got a matching key!
                if cfg['enc_domain_keymap'][domain] in keys:
                    log("Using default domain key for recipient '%s'" % to)
                    gpg_to.append((to, cfg['enc_domain_keymap'][domain]))
                    continue
                else:
                    log("Key '%s' in encrypt domain keymap not found in keyring for email address '%s'."
                        % (cfg['enc_domain_keymap'][domain], to))

        # At this point no key has been found
        if verbose:
            log("Recipient (%s) not in PGP domain list for encrypting." % to)
        ungpg_to.append(to)

    if gpg_to != list():
        log("Encrypting email to: %s" % ' '.join(map(lambda x: x[0], gpg_to)))

        # Getting PGP style for recipient
        gpg_to_smtp_mime = list()
        gpg_to_cmdline_mime = list()

        gpg_to_smtp_inline = list()
        gpg_to_cmdline_inline = list()

        for rcpt in gpg_to:
            # Checking pre defined styles in settings first
            if get_bool_from_cfg('pgp_style', rcpt[0], 'mime'):
                gpg_to_smtp_mime.append(rcpt[0])
                gpg_to_cmdline_mime.extend(rcpt[1].split(','))
            elif get_bool_from_cfg('pgp_style', rcpt[0], 'inline'):
                gpg_to_smtp_inline.append(rcpt[0])
                gpg_to_cmdline_inline.extend(rcpt[1].split(','))
            else:
                # Log message only if an unknown style is defined
                if get_bool_from_cfg('pgp_style', rcpt[0]):
                    log("Style %s for recipient %s is not known. Use default as fallback."
                        % (cfg['pgp_style'][rcpt[0]], rcpt[0]))

                # If no style is in settings defined for recipient, use default from settings
                if get_bool_from_cfg('default', 'mime_conversion', 'yes'):
                    gpg_to_smtp_mime.append(rcpt[0])
                    gpg_to_cmdline_mime.extend(rcpt[1].split(','))
                else:
                    gpg_to_smtp_inline.append(rcpt[0])
                    gpg_to_cmdline_inline.extend(rcpt[1].split(','))

        if gpg_to_smtp_mime != list():
            # Encrypt mail with PGP/MIME
            raw_message_mime = copy.deepcopy(raw_message)

            if get_bool_from_cfg('default', 'add_header', 'yes'):
                raw_message_mime[
                    'X-GPG-Mailgate'] = 'Encrypted by GPG Mailgate'

            encrypted_payloads = encrypt_all_payloads_mime(
                raw_message_mime, gpg_to_cmdline_mime)
            raw_message_mime.set_payload(encrypted_payloads)

            send_msg(raw_message_mime.as_string(), gpg_to_smtp_mime)

        if gpg_to_smtp_inline != list():
            # Encrypt mail with PGP/INLINE
            raw_message_inline = copy.deepcopy(raw_message)

            if get_bool_from_cfg('default', 'add_header', 'yes'):
                raw_message_inline[
                    'X-GPG-Mailgate'] = 'Encrypted by GPG Mailgate'

            encrypted_payloads = encrypt_all_payloads_inline(
                raw_message_inline, gpg_to_cmdline_inline)
            raw_message_inline.set_payload(encrypted_payloads)

            send_msg(raw_message_inline.as_string(), gpg_to_smtp_inline)

    return ungpg_to
		msg = email.message.Message()
		msg.set_payload( payloads )
		return encrypt_payload( msg, gpg_to_cmdline ).as_string()
	for payload in payloads:
		if( type( payload.get_payload() ) == list ):
			encrypted_payloads.append( encrypt_all_payloads( payload.get_payload(), gpg_to_cmdline ) )
		else:
			encrypted_payloads.append( [encrypt_payload( payload, gpg_to_cmdline )] )
	return sum(encrypted_payloads, [])

def get_msg( message ):
	if not message.is_multipart():
		return message.get_payload()
	return '\n\n'.join( [str(m) for m in message.get_payload()] )

keys = GnuPG.public_keys( cfg['gpg']['keyhome'] )
gpg_to = list()
ungpg_to = list()
for enc in encrypted_to_addrs:
	domain = enc.split('@')[1]
	if domain in cfg['default']['domains'].split(','):
		if enc in keys:
			gpg_to.append( (enc, enc) )
		elif cfg.has_key('keymap') and cfg['keymap'].has_key(enc):
			gpg_to.append( (enc, cfg['keymap'][enc]) )
		else:
			ungpg_to.append(enc);
			
for to in to_addrs:
	domain = to.split('@')[1]
	if domain in cfg['default']['domains'].split(','):
Exemplo n.º 21
0
def gpg_encrypt( raw_message, recipients ):

	if not get_bool_from_cfg('gpg', 'keyhome'):
		log("No valid entry for gpg keyhome. Encryption aborted.")
		return recipients

	keys = GnuPG.public_keys( cfg['gpg']['keyhome'] )
	for fingerprint in keys:
		keys[fingerprint] = sanitize_case_sense(keys[fingerprint])

	gpg_to = list()
	ungpg_to = list()

	for to in recipients:

		# Check if recipient is in keymap
		if get_bool_from_cfg('enc_keymap', to):
			log("Encrypt keymap has key '%s'" % cfg['enc_keymap'][to] )
			# Check we've got a matching key!
			if cfg['enc_keymap'][to] in keys:
				gpg_to.append( (to, cfg['enc_keymap'][to]) )
				continue
			else:
				log("Key '%s' in encrypt keymap not found in keyring for email address '%s'." % (cfg['enc_keymap'][to], to))

		# Check if key in keychain is present
		if to in keys.values() and not get_bool_from_cfg('default', 'enc_keymap_only', 'yes'):
			gpg_to.append( (to, to) )
			continue

		# Check if there is a default key for the domain
		splitted_to = to.split('@')
		if len(splitted_to) > 1:
			domain = splitted_to[1]
			if get_bool_from_cfg('enc_domain_keymap', domain):
				log("Encrypt domain keymap has key '%s'" % cfg['enc_dec_keymap'][domain] )
				# Check we've got a matching key!
				if cfg['enc_domain_keymap'][domain] in keys:
					log("Using default domain key for recipient '%s'" % to)
					gpg_to.append( (to, cfg['enc_domain_keymap'][domain]) )
					continue
				else:
					log("Key '%s' in encrypt domain keymap not found in keyring for email address '%s'." % (cfg['enc_domain_keymap'][domain], to))
		
		# At this point no key has been found
		if verbose:
			log("Recipient (%s) not in PGP domain list for encrypting." % to)
		ungpg_to.append(to)

	if gpg_to != list():
		log("Encrypting email to: %s" % ' '.join( map(lambda x: x[0], gpg_to) ))

		# Getting PGP style for recipient
		gpg_to_smtp_mime = list()
		gpg_to_cmdline_mime = list()

		gpg_to_smtp_inline = list()
		gpg_to_cmdline_inline = list()

		for rcpt in gpg_to:
			# Checking pre defined styles in settings first
			if get_bool_from_cfg('pgp_style', rcpt[0], 'mime'):
				gpg_to_smtp_mime.append(rcpt[0])
				gpg_to_cmdline_mime.extend(rcpt[1].split(','))
			elif get_bool_from_cfg('pgp_style', rcpt[0], 'inline'):
				gpg_to_smtp_inline.append(rcpt[0])
				gpg_to_cmdline_inline.extend(rcpt[1].split(','))
			else:
				# Log message only if an unknown style is defined
				if get_bool_from_cfg('pgp_style', rcpt[0]):
					log("Style %s for recipient %s is not known. Use default as fallback." % (cfg['pgp_style'][rcpt[0]], rcpt[0]))

				# If no style is in settings defined for recipient, use default from settings
				if get_bool_from_cfg('default', 'mime_conversion', 'yes'):
					gpg_to_smtp_mime.append(rcpt[0])
					gpg_to_cmdline_mime.extend(rcpt[1].split(','))
				else:
					gpg_to_smtp_inline.append(rcpt[0])
					gpg_to_cmdline_inline.extend(rcpt[1].split(','))

		if gpg_to_smtp_mime != list():
			# Encrypt mail with PGP/MIME
			raw_message_mime = copy.deepcopy(raw_message)

			if get_bool_from_cfg('default', 'add_header', 'yes'):
				raw_message_mime['X-GPG-Mailgate'] = 'Encrypted by GPG Mailgate'

			encrypted_payloads = encrypt_all_payloads_mime( raw_message_mime, gpg_to_cmdline_mime )
			raw_message_mime.set_payload( encrypted_payloads )

			send_msg( raw_message_mime.as_string(), gpg_to_smtp_mime )

		if gpg_to_smtp_inline != list():
			# Encrypt mail with PGP/INLINE
			raw_message_inline = copy.deepcopy(raw_message)

			if get_bool_from_cfg('default', 'add_header', 'yes'):
				raw_message_inline['X-GPG-Mailgate'] = 'Encrypted by GPG Mailgate'

			encrypted_payloads = encrypt_all_payloads_inline( raw_message_inline, gpg_to_cmdline_inline )
			raw_message_inline.set_payload( encrypted_payloads )

			send_msg( raw_message_inline.as_string(), gpg_to_smtp_inline )

	return ungpg_to