Ejemplo n.º 1
0
def main():
    global Cnf
    keyrings = None

    Cnf = utils.get_conf()

    Arguments = [('h', "help", "Add-User::Options::Help"),
                 ('k', "key", "Add-User::Options::Key", "HasArg"),
                 ('u', "user", "Add-User::Options::User", "HasArg"),
                 ]

    for i in ["help"]:
        key = "Add-User::Options::%s" % i
        if key not in Cnf:
            Cnf[key] = ""

    apt_pkg.parse_commandline(Cnf, Arguments, sys.argv)

    Options = Cnf.subtree("Add-User::Options")
    if Options["help"]:
        usage()

    session = DBConn().session()

    if not keyrings:
        keyrings = get_active_keyring_paths()

    cmd = ["gpg", "--with-colons", "--no-secmem-warning",
           "--no-auto-check-trustdb", "--with-fingerprint",
           "--no-default-keyring"]
    cmd.extend(utils.gpg_keyring_args(keyrings).split())
    cmd.extend(["--list-key", "--", Cnf["Add-User::Options::Key"]])
    output = subprocess.check_output(cmd).rstrip()
    m = re_gpg_fingerprint_colon.search(output)
    if not m:
        print(output)
        utils.fubar("0x%s: (1) No fingerprint found in gpg output but it returned 0?\n%s"
                                        % (Cnf["Add-User::Options::Key"], utils.prefix_multi_line_string(output,
                                                                                                                                                                " [GPG output:] ")))
    primary_key = m.group(1)
    primary_key = primary_key.replace(" ", "")

    uid = ""
    if "Add-User::Options::User" in Cnf and Cnf["Add-User::Options::User"]:
        uid = Cnf["Add-User::Options::User"]
        name = Cnf["Add-User::Options::User"]
    else:
        u = re_user_address.search(output)
        if not u:
            print(output)
            utils.fubar("0x%s: (2) No userid found in gpg output but it returned 0?\n%s"
                        % (Cnf["Add-User::Options::Key"], utils.prefix_multi_line_string(output, " [GPG output:] ")))
        uid = u.group(1)
        n = re_user_name.search(output)
        name = n.group(1)

# Look for all email addresses on the key.
    emails = []
    for line in output.split('\n'):
        e = re_user_mails.search(line)
        if not e:
            continue
        emails.append(e.group(2))

    print("0x%s -> %s <%s> -> %s -> %s" % (Cnf["Add-User::Options::Key"], name, emails[0], uid, primary_key))

    prompt = "Add user %s with above data (y/N) ? " % (uid)
    yn = utils.our_raw_input(prompt).lower()

    if yn == "y":
        # Create an account for the user?
        summary = ""

        # Now add user to the database.
        # Note that we provide a session, so we're responsible for committing
        uidobj = get_or_set_uid(uid, session=session)
        uid_id = uidobj.uid_id
        session.commit()

        # Lets add user to the email-whitelist file if its configured.
        if "Dinstall::MailWhiteList" in Cnf and Cnf["Dinstall::MailWhiteList"] != "":
            f = utils.open_file(Cnf["Dinstall::MailWhiteList"], "a")
            for mail in emails:
                f.write(mail + '\n')
            f.close()

        print("Added:\nUid:\t %s (ID: %s)\nMaint:\t %s\nFP:\t %s" % (uid, uid_id,
                     name, primary_key))

        # Should we send mail to the newly added user?
        if Cnf.find_b("Add-User::SendEmail"):
            mail = name + "<" + emails[0] + ">"
            Subst = {}
            Subst["__NEW_MAINTAINER__"] = mail
            Subst["__UID__"] = uid
            Subst["__KEYID__"] = Cnf["Add-User::Options::Key"]
            Subst["__PRIMARY_KEY__"] = primary_key
            Subst["__FROM_ADDRESS__"] = Cnf["Dinstall::MyEmailAddress"]
            Subst["__ADMIN_ADDRESS__"] = Cnf["Dinstall::MyAdminAddress"]
            Subst["__HOSTNAME__"] = Cnf["Dinstall::MyHost"]
            Subst["__DISTRO__"] = Cnf["Dinstall::MyDistribution"]
            Subst["__SUMMARY__"] = summary
            new_add_message = utils.TemplateSubst(Subst, Cnf["Dir::Templates"] + "/add-user.added")
            utils.send_mail(new_add_message)

    else:
        uid = None
Ejemplo n.º 2
0
def main():
    global Cnf
    keyrings = None

    Cnf = utils.get_conf()

    Arguments = [
        ('h', "help", "Add-User::Options::Help"),
        ('k', "key", "Add-User::Options::Key", "HasArg"),
        ('u', "user", "Add-User::Options::User", "HasArg"),
    ]

    for i in ["help"]:
        key = "Add-User::Options::%s" % i
        if key not in Cnf:
            Cnf[key] = ""

    apt_pkg.parse_commandline(Cnf, Arguments, sys.argv)

    Options = Cnf.subtree("Add-User::Options")
    if Options["help"]:
        usage()

    session = DBConn().session()

    if not keyrings:
        keyrings = get_active_keyring_paths()

    cmd = [
        "gpg", "--with-colons", "--no-secmem-warning",
        "--no-auto-check-trustdb", "--with-fingerprint", "--no-default-keyring"
    ]
    cmd.extend(utils.gpg_keyring_args(keyrings).split())
    cmd.extend(["--list-key", "--", Cnf["Add-User::Options::Key"]])
    output = subprocess.check_output(cmd).rstrip()
    m = re_gpg_fingerprint_colon.search(output)
    if not m:
        print(output)
        utils.fubar(
            "0x%s: (1) No fingerprint found in gpg output but it returned 0?\n%s"
            % (Cnf["Add-User::Options::Key"],
               utils.prefix_multi_line_string(output, " [GPG output:] ")))
    primary_key = m.group(1)
    primary_key = primary_key.replace(" ", "")

    uid = ""
    if "Add-User::Options::User" in Cnf and Cnf["Add-User::Options::User"]:
        uid = Cnf["Add-User::Options::User"]
        name = Cnf["Add-User::Options::User"]
    else:
        u = re_user_address.search(output)
        if not u:
            print(output)
            utils.fubar(
                "0x%s: (2) No userid found in gpg output but it returned 0?\n%s"
                % (Cnf["Add-User::Options::Key"],
                   utils.prefix_multi_line_string(output, " [GPG output:] ")))
        uid = u.group(1)
        n = re_user_name.search(output)
        name = n.group(1)

# Look for all email addresses on the key.
    emails = []
    for line in output.split('\n'):
        e = re_user_mails.search(line)
        if not e:
            continue
        emails.append(e.group(2))

    print("0x%s -> %s <%s> -> %s -> %s" %
          (Cnf["Add-User::Options::Key"], name, emails[0], uid, primary_key))

    prompt = "Add user %s with above data (y/N) ? " % (uid)
    yn = utils.our_raw_input(prompt).lower()

    if yn == "y":
        # Create an account for the user?
        summary = ""

        # Now add user to the database.
        # Note that we provide a session, so we're responsible for committing
        uidobj = get_or_set_uid(uid, session=session)
        uid_id = uidobj.uid_id
        session.commit()

        # Lets add user to the email-whitelist file if its configured.
        if "Dinstall::MailWhiteList" in Cnf and Cnf[
                "Dinstall::MailWhiteList"] != "":
            f = utils.open_file(Cnf["Dinstall::MailWhiteList"], "a")
            for mail in emails:
                f.write(mail + '\n')
            f.close()

        print("Added:\nUid:\t %s (ID: %s)\nMaint:\t %s\nFP:\t %s" %
              (uid, uid_id, name, primary_key))

        # Should we send mail to the newly added user?
        if Cnf.find_b("Add-User::SendEmail"):
            mail = name + "<" + emails[0] + ">"
            Subst = {}
            Subst["__NEW_MAINTAINER__"] = mail
            Subst["__UID__"] = uid
            Subst["__KEYID__"] = Cnf["Add-User::Options::Key"]
            Subst["__PRIMARY_KEY__"] = primary_key
            Subst["__FROM_ADDRESS__"] = Cnf["Dinstall::MyEmailAddress"]
            Subst["__ADMIN_ADDRESS__"] = Cnf["Dinstall::MyAdminAddress"]
            Subst["__HOSTNAME__"] = Cnf["Dinstall::MyHost"]
            Subst["__DISTRO__"] = Cnf["Dinstall::MyDistribution"]
            Subst["__SUMMARY__"] = summary
            new_add_message = utils.TemplateSubst(
                Subst, Cnf["Dir::Templates"] + "/add-user.added")
            utils.send_mail(new_add_message)

    else:
        uid = None
Ejemplo n.º 3
0
def main():
    cnf = Config()
    Arguments = [('h',"help","Import-LDAP-Fingerprints::Options::Help")]
    for i in [ "help" ]:
        if not cnf.has_key("Import-LDAP-Fingerprints::Options::%s" % (i)):
            cnf["Import-LDAP-Fingerprints::Options::%s" % (i)] = ""

    apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)

    Options = cnf.subtree("Import-LDAP-Fingerprints::Options")
    if Options["Help"]:
        usage()

    session = DBConn().session()

    LDAPDn = cnf["Import-LDAP-Fingerprints::LDAPDn"]
    LDAPServer = cnf["Import-LDAP-Fingerprints::LDAPServer"]
    l = ldap.open(LDAPServer)
    l.simple_bind_s("","")
    Attrs = l.search_s(LDAPDn, ldap.SCOPE_ONELEVEL,
                       "(&(keyfingerprint=*)(gidnumber=%s))" % (cnf["Import-Users-From-Passwd::ValidGID"]),
                       ["uid", "keyfingerprint", "cn", "mn", "sn"])


    # Our database session is already in a transaction

    # Sync LDAP with DB
    db_fin_uid = {}
    db_uid_name = {}
    ldap_fin_uid_id = {}
    q = session.execute("""
SELECT f.fingerprint, f.id, u.uid FROM fingerprint f, uid u WHERE f.uid = u.id
 UNION SELECT f.fingerprint, f.id, null FROM fingerprint f where f.uid is null""")
    for i in q.fetchall():
        (fingerprint, fingerprint_id, uid) = i
        db_fin_uid[fingerprint] = (uid, fingerprint_id)

    q = session.execute("SELECT id, name FROM uid")
    for i in q.fetchall():
        (uid, name) = i
        db_uid_name[uid] = name

    for i in Attrs:
        entry = i[1]
        fingerprints = entry["keyFingerPrint"]
        uid_name = entry["uid"][0]
        name = get_ldap_name(entry)
        uid = get_or_set_uid(uid_name, session)
        uid_id = uid.uid_id

        if not db_uid_name.has_key(uid_id) or db_uid_name[uid_id] != name:
            session.execute("UPDATE uid SET name = :name WHERE id = :uidid", {'name': name, 'uidid': uid_id})
            print "Assigning name of %s as %s" % (uid_name, name)

        for fingerprint in fingerprints:
            ldap_fin_uid_id[fingerprint] = (uid_name, uid_id)
            if db_fin_uid.has_key(fingerprint):
                (existing_uid, fingerprint_id) = db_fin_uid[fingerprint]
                if not existing_uid:
                    session.execute("UPDATE fingerprint SET uid = :uidid WHERE id = :fprid",
                                    {'uidid': uid_id, 'fprid': fingerprint_id})
                    print "Assigning %s to 0x%s." % (uid_name, fingerprint)
                elif existing_uid == uid_name:
                    pass
                elif '@' not in existing_uid:
                    session.execute("UPDATE fingerprint SET uid = :uidid WHERE id = :fprid",
                                    {'uidid': uid_id, 'fprid': fingerprint_id})
                    print "Promoting DM %s to DD %s with keyid 0x%s." % (existing_uid, uid_name, fingerprint)
                else:
                    utils.warn("%s has %s in LDAP, but database says it should be %s." % \
                               (uid_name, fingerprint, existing_uid))

    # Try to update people who sign with non-primary key
    q = session.execute("SELECT fingerprint, id FROM fingerprint WHERE uid is null")
    for i in q.fetchall():
        (fingerprint, fingerprint_id) = i
        cmd = "gpg --no-default-keyring %s --fingerprint %s" \
              % (utils.gpg_keyring_args(), fingerprint)
        (result, output) = commands.getstatusoutput(cmd)
        if result == 0:
            m = re_gpg_fingerprint.search(output)
            if not m:
                print output
                utils.fubar("0x%s: No fingerprint found in gpg output but it returned 0?\n%s" % \
                            (fingerprint, utils.prefix_multi_line_string(output, " [GPG output:] ")))
            primary_key = m.group(1)
            primary_key = primary_key.replace(" ","")
            if not ldap_fin_uid_id.has_key(primary_key):
                utils.warn("0x%s (from 0x%s): no UID found in LDAP" % (primary_key, fingerprint))
            else:
                (uid, uid_id) = ldap_fin_uid_id[primary_key]
                session.execute("UPDATE fingerprint SET uid = :uid WHERE id = :fprid",
                                {'uid': uid_id, 'fprid': fingerprint_id})
                print "Assigning %s to 0x%s." % (uid, fingerprint)
        else:
            extra_keyrings = ""
            for keyring in cnf.value_list("Import-LDAP-Fingerprints::ExtraKeyrings"):
                extra_keyrings += " --keyring=%s" % (keyring)
            cmd = "gpg %s %s --list-key %s" \
                  % (utils.gpg_keyring_args(), extra_keyrings, fingerprint)
            (result, output) = commands.getstatusoutput(cmd)
            if result != 0:
                cmd = "gpg --keyserver=%s --allow-non-selfsigned-uid --recv-key %s" % (cnf["Import-LDAP-Fingerprints::KeyServer"], fingerprint)
                (result, output) = commands.getstatusoutput(cmd)
                if result != 0:
                    print "0x%s: NOT found on keyserver." % (fingerprint)
                    print cmd
                    print result
                    print output
                    continue
                else:
                    cmd = "gpg --list-key %s" % (fingerprint)
                    (result, output) = commands.getstatusoutput(cmd)
                    if result != 0:
                        print "0x%s: --list-key returned error after --recv-key didn't." % (fingerprint)
                        print cmd
                        print result
                        print output
                        continue
            m = re_debian_address.search(output)
            if m:
                guess_uid = m.group(1)
            else:
                guess_uid = "???"
            name = " ".join(output.split('\n')[0].split()[3:])
            print "0x%s -> %s -> %s" % (fingerprint, name, guess_uid)

            # FIXME: make me optionally non-interactive
            # FIXME: default to the guessed ID
            uid = None
            while not uid:
                uid = utils.our_raw_input("Map to which UID ? ")
                Attrs = l.search_s(LDAPDn,ldap.SCOPE_ONELEVEL,"(uid=%s)" % (uid), ["cn","mn","sn"])
                if not Attrs:
                    print "That UID doesn't exist in LDAP!"
                    uid = None
                else:
                    entry = Attrs[0][1]
                    name = get_ldap_name(entry)
                    prompt = "Map to %s - %s (y/N) ? " % (uid, name.replace("  "," "))
                    yn = utils.our_raw_input(prompt).lower()
                    if yn == "y":
                        uid_o = get_or_set_uid(uid, session=session)
                        uid_id = uid_o.uid_id
                        session.execute("UPDATE fingerprint SET uid = :uidid WHERE id = :fprid",
                                        {'uidid': uid_id, 'fprid': fingerprint_id})
                        print "Assigning %s to 0x%s." % (uid, fingerprint)
                    else:
                        uid = None

    # Commit it all
    session.commit()