Ejemplo n.º 1
0
def __get_identities(menu):
    ids = []
    lines = re.split(r"[\r\n]+", menu)
    for l in lines:
        l = l.strip()
        m = re.match(r"^\[.*?\]\s+\((\d+)\).*<(.*?)>$", l)
        if m:
            if (is_email_address(m.group(2))):
                ids.append((m.group(1), m.group(2)))
    return ids
Ejemplo n.º 2
0
def __get_identities(menu):
    ids = []
    lines = re.split(r"[\r\n]+", menu)
    for l in lines:
        l = l.strip()
        m = re.match(r"^\[.*?\]\s+\((\d+)\).*<(.*?)>$", l)
        if m:
            if (is_email_address(m.group(2))):
                ids.append( (m.group(1), m.group(2)) )
    return ids
Ejemplo n.º 3
0
def __get_raw_email_addr(addr):
    addr = addr.strip()
    matches = re.search(r"<([^>]+)>", addr)
    if not matches:
        return addr
    result = matches.group(1).strip()
    if is_email_address(result):
        return result
    else:
        return addr
Ejemplo n.º 4
0
def __get_raw_email_addr(addr):
    addr = addr.strip()
    matches = re.search(r"<([^>]+)>", addr)
    if not matches:
        return addr
    result = matches.group(1).strip()
    if is_email_address(result):
        return result
    else:
        return addr
Ejemplo n.º 5
0
def validate_mail(message):

    # Step 1: Read the from address, so that we at least know where to 
    #         send the error message to
    from_addr = None
    try:
        # Get the one and only from address
        (headers, body) = dkim.rfc822_parse(message)
        from_addr  = __get_raw_email_addr(__get_required_header(headers, "From"))
        if not is_email_address(from_addr):
            return (None, False, "'" + str(from_addr) + "' is not valid From: address")
    except Exception, e:
            return (None, False, e.__str__())
Ejemplo n.º 6
0
def validate_mail(message):

    # Step 1: Read the from address, so that we at least know where to
    #         send the error message to
    from_addr = None
    try:
        # Get the one and only from address
        (headers, body) = dkim.rfc822_parse(message)
        from_addr = __get_raw_email_addr(__get_required_header(
            headers, "From"))
        if not is_email_address(from_addr):
            return (None, False,
                    "'" + str(from_addr) + "' is not valid From: address")
    except Exception, e:
        return (None, False, e.__str__())
Ejemplo n.º 7
0
def signkey(pubkey, email_addr, signing_key_fp):
    session_logger = StringIO()
    encrypted_key  = None # The ultimate result

    signing_key_fp    = re.sub(r"\s+", "", signing_key_fp)
    signing_key_fp_16 = signing_key_fp[-16:]

    # Step 0: Sanity Check
    ####################################################
    if not is_email_address(email_addr):
        raise SignKeyException("'" + email_addr + "' does not appear to be a valid email address.", session_logger.getvalue())


    # Step 1: Sniff the pubkey to make sure it looks ok 
    ####################################################
    proc = subprocess.Popen(['/usr/bin/gpg2', '--with-fingerprint', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    proc.stdin.write(pubkey)
    (sout,serr) = proc.communicate()
    session_logger.write("Peeking at the key:\n" + sout + "\n\n")

    # Make sure the email is in there
    if not re.match(r"^pub", sout):
        raise SignKeyException("Input does not appear to be a public key.", session_logger.getvalue())

    # Make sure the email is in there
    if not re.search(r"^(pub|uid).*?<(" + re.escape(email_addr) + r")>\s*$", sout, re.MULTILINE):
        raise SignKeyException("Could not find email address '" + email_addr + "' in the public key.", session_logger.getvalue())

    # Get the key fingerprint
    m = re.search(r"^\s*Key fingerprint\s*=\s*((\s+[a-fA-F0-9]{4}){10})\s*$", sout, re.MULTILINE)
    fingerprint = None
    if m:
        fingerprint = re.sub(r"\s+", "", m.group(1))
    
    if fingerprint is None:
        raise SignKeyException("Could not extract fingerprint from public key.", session_logger.getvalue())


    # Step 2: Create a new temprary keyring to work from
    #####################################################

    # Read the keyring
    fh = open(os.path.join(os.environ["HOME"], ".gnupg", "pubring.gpg"), "rb")
    pub_keyring = fh.read()
    fh.close()

    # Write the existing keyring to our temp keyring
    temp_keyring = tempfile.NamedTemporaryFile('rw+b')
    try:

        temp_keyring.write(pub_keyring)
        temp_keyring.flush()
        temp_keyring.seek(0)


    # Step 3: Import the supplied key
    #####################################################

        # Import they key
        proc = subprocess.Popen(['/usr/bin/gpg2', '--no-default-keyring', '--keyring', temp_keyring.name, '--import', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        proc.stdin.write(pubkey)
        (sout,serr) = proc.communicate()
        session_logger.write("Importing the key:\n" + sout + "\n\n")

        if not re.search(r"^.*: public key \".*\" imported\s*$", sout, re.MULTILINE):
            raise SignKeyException("Could not import public key.", session_logger.getvalue())

    # Step 4: Sign the key
    #####################################################


        session_logger.write("Signing the key:\n")
        __do_sign_key(temp_keyring.name, fingerprint, email_addr, session_logger)
        session_logger.write("\n\n")
        

    # Step 5: Encrypt the signed key
    #####################################################

        # Check that the sig exists 
        proc = subprocess.Popen(['/usr/bin/gpg2', '--no-default-keyring', '--keyring', temp_keyring.name, '--list-sigs', fingerprint], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        (sout,serr) = proc.communicate()
        session_logger.write("Checking that the sig exists:\n" + sout + "\n\n")

        # Export the key into ASCII 
        proc = subprocess.Popen(['/usr/bin/gpg2', '--no-default-keyring', '--keyring', temp_keyring.name, '--armor', '--export', fingerprint], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        (signed_key,serr) = proc.communicate()
        session_logger.write("Exporting the key (blank means OK):\n" + serr + "\n\n")

        # Sanity check that we've actually signed it
        proc = subprocess.Popen(['/usr/bin/gpg2', '--list-packets', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        proc.stdin.write(signed_key)
        (sout,serr) = proc.communicate()
        session_logger.write("Listing the packets:\n" + sout + "\n\n")

        if "\n:signature packet: algo 1, keyid " + signing_key_fp_16 + "\n" not in sout:
            raise SignKeyException("Could not find the signature packet. Something went wrong.", session_logger.getvalue())

        # Encrypt the signed key, to be opened only by the correct owner
	proc = subprocess.Popen(['/usr/bin/gpg2', '--no-default-keyring', '--keyring', temp_keyring.name, '--armor', '--recipient', fingerprint, '--trust-model', 'always', '--encrypt', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        proc.stdin.write(signed_key)
        (encrypted_key,serr) = proc.communicate()
        session_logger.write("Exporting the key (blank means OK):\n" + serr + "\n\n")


    except Exception, e:
        temp_keyring.close()
        if isinstance(e, SignKeyException):
            raise e
        else:
            session_logger.write("Uncaught Python error:\n" + traceback.format_exc() + "\n\n")
            raise SignKeyException(str(e), session_logger.getvalue())
Ejemplo n.º 8
0
def signkey(pubkey, email_addr, signing_key_fp):
    session_logger = StringIO()
    encrypted_key = None  # The ultimate result

    signing_key_fp = re.sub(r"\s+", "", signing_key_fp)
    signing_key_fp_16 = signing_key_fp[-16:]

    # Step 0: Sanity Check
    ####################################################
    if not is_email_address(email_addr):
        raise SignKeyException(
            "'" + email_addr +
            "' does not appear to be a valid email address.",
            session_logger.getvalue())

    # Step 1: Sniff the pubkey to make sure it looks ok
    ####################################################
    proc = subprocess.Popen(['/usr/bin/gpg2', '--with-fingerprint', '-'],
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    proc.stdin.write(pubkey)
    (sout, serr) = proc.communicate()
    session_logger.write("Peeking at the key:\n" + sout + "\n\n")

    # Make sure the email is in there
    if not re.match(r"^pub", sout):
        raise SignKeyException("Input does not appear to be a public key.",
                               session_logger.getvalue())

    # Make sure the email is in there
    if not re.search(r"^(pub|uid).*?<(" + re.escape(email_addr) + r")>\s*$",
                     sout, re.MULTILINE):
        raise SignKeyException(
            "Could not find email address '" + email_addr +
            "' in the public key.", session_logger.getvalue())

    # Get the key fingerprint
    m = re.search(r"^\s*Key fingerprint\s*=\s*((\s+[a-fA-F0-9]{4}){10})\s*$",
                  sout, re.MULTILINE)
    fingerprint = None
    if m:
        fingerprint = re.sub(r"\s+", "", m.group(1))

    if fingerprint is None:
        raise SignKeyException(
            "Could not extract fingerprint from public key.",
            session_logger.getvalue())

    # Step 2: Create a new temprary keyring to work from
    #####################################################

    # Read the keyring
    fh = open(os.path.join(os.environ["HOME"], ".gnupg", "pubring.gpg"), "rb")
    pub_keyring = fh.read()
    fh.close()

    # Write the existing keyring to our temp keyring
    temp_keyring = tempfile.NamedTemporaryFile('rw+b')
    try:

        temp_keyring.write(pub_keyring)
        temp_keyring.flush()
        temp_keyring.seek(0)

        # Step 3: Import the supplied key
        #####################################################

        # Import they key
        proc = subprocess.Popen([
            '/usr/bin/gpg2', '--no-default-keyring', '--keyring',
            temp_keyring.name, '--import', '-'
        ],
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
        proc.stdin.write(pubkey)
        (sout, serr) = proc.communicate()
        session_logger.write("Importing the key:\n" + sout + "\n\n")

        if not re.search(r"^.*: public key \".*\" imported\s*$", sout,
                         re.MULTILINE):
            raise SignKeyException("Could not import public key.",
                                   session_logger.getvalue())

    # Step 4: Sign the key
    #####################################################

        session_logger.write("Signing the key:\n")
        __do_sign_key(temp_keyring.name, fingerprint, email_addr,
                      session_logger)
        session_logger.write("\n\n")

        # Step 5: Encrypt the signed key
        #####################################################

        # Check that the sig exists
        proc = subprocess.Popen([
            '/usr/bin/gpg2', '--no-default-keyring', '--keyring',
            temp_keyring.name, '--list-sigs', fingerprint
        ],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
        (sout, serr) = proc.communicate()
        session_logger.write("Checking that the sig exists:\n" + sout + "\n\n")

        # Export the key into ASCII
        proc = subprocess.Popen([
            '/usr/bin/gpg2', '--no-default-keyring', '--keyring',
            temp_keyring.name, '--armor', '--export', fingerprint
        ],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        (signed_key, serr) = proc.communicate()
        session_logger.write("Exporting the key (blank means OK):\n" + serr +
                             "\n\n")

        # Sanity check that we've actually signed it
        proc = subprocess.Popen(['/usr/bin/gpg2', '--list-packets', '-'],
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
        proc.stdin.write(signed_key)
        (sout, serr) = proc.communicate()
        session_logger.write("Listing the packets:\n" + sout + "\n\n")

        if "\n:signature packet: algo 1, keyid " + signing_key_fp_16 + "\n" not in sout:
            raise SignKeyException(
                "Could not find the signature packet. Something went wrong.",
                session_logger.getvalue())

        # Encrypt the signed key, to be opened only by the correct owner
        proc = subprocess.Popen([
            '/usr/bin/gpg2', '--no-default-keyring', '--keyring',
            temp_keyring.name, '--armor', '--recipient', fingerprint,
            '--trust-model', 'always', '--encrypt', '-'
        ],
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        proc.stdin.write(signed_key)
        (encrypted_key, serr) = proc.communicate()
        session_logger.write("Exporting the key (blank means OK):\n" + serr +
                             "\n\n")

    except Exception, e:
        temp_keyring.close()
        if isinstance(e, SignKeyException):
            raise e
        else:
            session_logger.write("Uncaught Python error:\n" +
                                 traceback.format_exc() + "\n\n")
            raise SignKeyException(str(e), session_logger.getvalue())