Beispiel #1
0
    def index(self, pattern):
        payload = {"op": "index", "search": pattern, "options": "mr"}
        r = requests.get(self.lookupurl, verify=True, params=payload)

        # No keys found
        if r.status_code == 404:
            return None
        elif r.status_code == 500:
            raise TooManyKeys("Too many keys")
        elif r.status_code == 200:
            text = r.text.split("\n", 1)[1].strip()
            keylist = []
            key_text = text.split("pub:")[1:]
            for key in key_text:
                pub, *uids = key.strip().split("\n")
                pub = pub.strip().split(":")
                final_uids = []
                for uid in uids:
                    uid = uid.strip().split(":")
                    if uid[0] == "uid":
                        final_uids.append(tuple(uid[1:]))

                finalkey = Key(pub, final_uids)
                keylist.append(finalkey)
            return keylist

        else:
            print_debug(r)
            raise Exception("Unknown Error")
Beispiel #2
0
def interact(key, commands):
    c = gpg.Context()
    keys = list(c.keylist(key))
    print_debug(keys, end="\n\n")

    if len(keys) != 1:
        if len(keys) == 0:
            error_msg = r"No key matching {key}"
        else:
            error_msg = r"More than 1 matching keys for {key}"
        fail(error_msg.format(key=key))

    editor = KeyEditor(commands, 2)
    c.interact(keys[0], editor.edit_fnc)
    assert editor.done
Beispiel #3
0
def receive(serverurl, keystring):
    pattern8 = re.compile(r"(^[0-9a-fA-F]{8}$)|(^[0-9a-fA-F]{16}$)")
    if re.match(pattern8, keystring) is None:
        fail("Invalid key pattern!")

    server = Server(serverurl)
    fullKey = server.get(keystring)

    if fullKey in [None, []]:
        fail("No keys found")

    c = gpg.Context()
    c.op_import(fullKey.encode())
    result = c.op_import_result()
    if result is None:
        fail("Could not import contact")
        print_debug(result)
Beispiel #4
0
def search(serverurl, searchstring):
    server = Server(serverurl)
    print_debug(server.serverurl)

    keys = server.index(searchstring)

    if keys in [None, []]:
        fail("No keys found")
    else:
        keysToImport = server.getchoice(keys)

    c = gpg.Context()
    for key in keysToImport:
        c.op_import(key.fullKey.encode())
        result = c.op_import_result()
        if result is None:
            fail("Could not import contact")
        print_debug(result)
Beispiel #5
0
    def edit_fnc(self, status, args, out=None):
        print_debug("Code: {status}, args: {args}\n".format(status=status,
                                                            args=args))

        # There may be multiple attempts to pinentry
        if status == "PINENTRY_LAUNCHED":
            cmd = None
        else:
            cmd = self.cmds[self.step]
            self.step += 1
            self.done = True if len(self.cmds) == self.step else False

        if debug:
            print_debug("cmd: {cmd}\n".format(cmd=cmd))
            try:
                input("Debug mode: Press any key to continue!")
            except EOFError:
                pass

        return cmd
Beispiel #6
0
import gpg

from fn.auxiliary import fail, handle_exception, print_debug
from fn.print_key import print_key


@handle_exception(gpg.errors.GpgError)
def list_contacts(contacts):
    c = gpg.Context()

    key_set = set()

    for contact in contacts:
        key_set.update(c.keylist(contact))

    if len(list(key_set)) == 0:
        fail("No matching contacts found!")

    for key in key_set:
        print_key(key.fpr, end="\n")


if __name__ == "__main__":
    contacts = [None]
    if len(sys.argv) > 1:
        contacts = sys.argv[1:]

    print_debug("contacts:", contacts, sep="\n")

    list_contacts(contacts)
Beispiel #7
0
def print_key(identity, end=""):
    """
    print the details of key whose identitiy is passed
    """
    c = gpg.Context()
    key = list(c.keylist(identity, mode=gpg.constants.keylist.mode.SIGS))

    # exit with status 1 if more than one key matches are found for identity
    if len(key) != 1:
        if len(key) == 0:
            error_msg = r"No key matching {identity}"
        else:
            error_msg = r"More than 1 matching keys for {identity}"
        fail(error_msg.format(identity=identity))

    key = key[0]

    print_debug(key, end='\n\n')

    # uid
    uid_list = ["uid: " + user_id.uid + "\n" for user_id in key.uids]
    all_uids = "".join(uid_list)

    # fpr
    fpr = " ".join(textwrap.wrap(key.fpr, 4))

    # keyid
    keyid = key.fpr[-16:]

    # trust
    trust_map = {
        "UNKNOWN": "UNKNOWN",
        "UNDEFINED": "UNKNOWN",
        "ULTIMATE": "ULTIMATE",
        "NEVER": "NONE",
        "MARGINAL": "MARGINAL",
        "FULL": "FULL"
        }

    trust = filter(lambda t: eval("gpg.constants.validity." + t) ==
                   key.owner_trust, trust_map.keys())
    trust = trust_map[list(trust)[0]].lower()
    trust = "trust: " + trust + "\n" if trust != "unknown" else ""

    # keys
    subkey_list = []
    for subkey in key.subkeys:
        starttime = time.strftime("%Y-%m-%d", time.localtime(subkey.timestamp))
        endtime = time.strftime("%Y-%m-%d", time.localtime(subkey.expires))

        # check if key never expires
        if subkey.expires == 0:
            endtime = "never"

        exp = "expired" if subkey.expired else ""

        if subkey.can_sign:
            u = "sign"
        elif subkey.can_authenticate:
            u = "auth"
        elif subkey.can_encrypt:
            u = "decr"

        subkey_map = {
            "u": u,
            "subkey_id": subkey.keyid,
            "start": starttime,
            "end": endtime,
            "exp": exp
        }

        subkey_list.append("{u}: {subkey_id} {start} {end} {exp}"
                           .format_map(subkey_map))

    subkeys = "\n".join(subkey_list) + "\n" if subkey_list else ""

    # verifications
    sign_list = set()
    for uid in key.uids:
        for sign in uid.signatures:
            if sign.keyid != keyid and sign.uid:
                if not (sign.revoked or sign.expired):
                    sign_list.add("certified by: " +
                                  sign.uid + " " + sign.keyid)

    signatures = "\n".join(sign_list) + "\n" if sign_list else ""

    key_map = {
        "identity": keyid,
        "all_uids": all_uids,
        "fpr": fpr,
        "trust": trust,
        "subkeys": subkeys,
        "signatures": signatures
    }

    print("id: {identity}\n"
          "{all_uids}"
          "fpr: {fpr}\n"
          "{trust}"
          "{subkeys}"
          "{signatures}"
          .format_map(key_map), end=end)
Beispiel #8
0
 def get(self, pattern):
     payload = {"op": "get", "search": "0x" + pattern, "options": "mr"}
     r = requests.get(self.lookupurl, verify=True, params=payload)
     print_debug(r)
     print_debug("Key text", r.text, sep="\n")
     return r.text