]> git.decadent.org.uk Git - dak.git/blob - dak/import_ldap_fingerprints.py
Modified dak to use non-braindead DM schema, and use an actual column for
[dak.git] / dak / import_ldap_fingerprints.py
1 #!/usr/bin/env python
2
3 # Sync fingerprint and uid tables with a debian.org LDAP DB
4 # Copyright (C) 2003, 2004, 2006  James Troup <james@nocrew.org>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20 ################################################################################
21
22 # <elmo>  ping@debian.org ?
23 # <aj>    missing@ ? wtfru@ ?
24 # <elmo>  giggle
25 # <elmo>  I like wtfru
26 # <aj>    all you have to do is retrofit wtfru into an acronym and no one
27 #         could possibly be offended!
28 # <elmo>  aj: worried terriers for russian unity ?
29 # <aj>    uhhh
30 # <aj>    ooookkkaaaaay
31 # <elmo>  wthru is a little less offensive maybe?  but myabe that's
32 #         just because I read h as heck, not hell
33 # <elmo>  ho hum
34 # <aj>    (surely the "f" stands for "freedom" though...)
35 # <elmo>  where the freedom are you?
36 # <aj>    'xactly
37 # <elmo>  or worried terriers freed (of) russian unilateralism ?
38 # <aj>    freedom -- it's the "foo" of the 21st century
39 # <aj>    oo, how about "wat@" as in wherefore art thou?
40 # <neuro> or worried attack terriers
41 # <aj>    Waning Trysts Feared - Return? Unavailable?
42 # <aj>    (i find all these terriers more worrying, than worried)
43 # <neuro> worrying attack terriers, then
44
45 ################################################################################
46
47 import commands, ldap, pg, re, sys
48 import apt_pkg
49 from daklib import database
50 from daklib import utils
51
52 ################################################################################
53
54 Cnf = None
55 projectB = None
56
57 re_gpg_fingerprint = re.compile(r"^\s+Key fingerprint = (.*)$", re.MULTILINE)
58 re_debian_address = re.compile(r"^.*<(.*)@debian\.org>$", re.MULTILINE)
59
60 ################################################################################
61
62 def usage(exit_code=0):
63     print """Usage: dak import-ldap-fingerprints
64 Syncs fingerprint and uid tables with a debian.org LDAP DB
65
66   -h, --help                show this help and exit."""
67     sys.exit(exit_code)
68
69 ################################################################################
70
71 def get_ldap_value(entry, value):
72     ret = entry.get(value)
73     if not ret or ret[0] == "" or ret[0] == "-":
74         return ""
75     else:
76         # FIXME: what about > 0 ?
77         return ret[0] + " "
78
79 def get_ldap_name(entry):
80     name = get_ldap_value(entry, "cn")
81     name += get_ldap_value(entry, "mn")
82     name += get_ldap_value(entry, "sn")
83     return name.rstrip()
84
85 def escape_string(str):
86     return str.replace("'", "\\'")
87
88 def main():
89     global Cnf, projectB
90
91     Cnf = utils.get_conf()
92     Arguments = [('h',"help","Import-LDAP-Fingerprints::Options::Help")]
93     for i in [ "help" ]:
94         if not Cnf.has_key("Import-LDAP-Fingerprints::Options::%s" % (i)):
95             Cnf["Import-LDAP-Fingerprints::Options::%s" % (i)] = ""
96
97     apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
98
99     Options = Cnf.SubTree("Import-LDAP-Fingerprints::Options")
100     if Options["Help"]:
101         usage()
102
103     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
104     database.init(Cnf, projectB)
105
106     LDAPDn = Cnf["Import-LDAP-Fingerprints::LDAPDn"]
107     LDAPServer = Cnf["Import-LDAP-Fingerprints::LDAPServer"]
108     l = ldap.open(LDAPServer)
109     l.simple_bind_s("","")
110     Attrs = l.search_s(LDAPDn, ldap.SCOPE_ONELEVEL,
111                        "(&(keyfingerprint=*)(gidnumber=%s))" % (Cnf["Import-Users-From-Passwd::ValidGID"]),
112                        ["uid", "keyfingerprint", "cn", "mn", "sn"])
113
114
115     projectB.query("BEGIN WORK")
116
117
118     # Sync LDAP with DB
119     db_fin_uid = {}
120     db_uid_name = {}
121     ldap_fin_uid_id = {}
122     q = projectB.query("""
123 SELECT f.fingerprint, f.id, u.uid, u.debian_maintainer FROM fingerprint f, uid u WHERE f.uid = u.id
124  UNION SELECT f.fingerprint, f.id, null FROM fingerprint f where f.uid is null""")
125     for i in q.getresult():
126         (fingerprint, fingerprint_id, uid) = i
127         db_fin_uid[fingerprint] = (uid, fingerprint_id, debian_maintainer)
128
129     q = projectB.query("SELECT id, name FROM uid")
130     for i in q.getresult():
131         (uid, name) = i
132         db_uid_name[uid] = name
133
134     for i in Attrs:
135         entry = i[1]
136         fingerprints = entry["keyFingerPrint"]
137         uid = entry["uid"][0]
138         name = get_ldap_name(entry)
139         uid_id = database.get_or_set_uid_id(uid)
140
141         if not db_uid_name.has_key(uid_id) or db_uid_name[uid_id] != name:
142             q = projectB.query("UPDATE uid SET name = '%s' WHERE id = %d" % (escape_string(name), uid_id))
143             print "Assigning name of %s as %s" % (uid, name)
144
145         for fingerprint in fingerprints:
146             ldap_fin_uid_id[fingerprint] = (uid, uid_id)
147             if db_fin_uid.has_key(fingerprint):
148                 (existing_uid, fingerprint_id, is_dm) = db_fin_uid[fingerprint]
149                 if not existing_uid:
150                     q = projectB.query("UPDATE fingerprint SET uid = %s WHERE id = %s" % (uid_id, fingerprint_id))
151                     print "Assigning %s to 0x%s." % (uid, fingerprint)
152                 elif existing_uid == uid:
153                     pass
154                 elif is_dm = "t":
155                     q = projectB.query("UPDATE fingerprint SET uid = %s AND debian_maintainer = 'f' WHERE id = %s" % (uid_id, fingerprint_id))
156                     print "Promoting DM %s to DD %s with keyid 0x%s." % (existing_uid, uid, fingerprint)
157                 else:
158                     utils.warn("%s has %s in LDAP, but projectB says it should be %s." % (uid, fingerprint, existing_uid))
159
160     # Try to update people who sign with non-primary key
161     q = projectB.query("SELECT fingerprint, id FROM fingerprint WHERE uid is null")
162     for i in q.getresult():
163         (fingerprint, fingerprint_id) = i
164         cmd = "gpg --no-default-keyring %s --fingerprint %s" \
165               % (utils.gpg_keyring_args(), fingerprint)
166         (result, output) = commands.getstatusoutput(cmd)
167         if result == 0:
168             m = re_gpg_fingerprint.search(output)
169             if not m:
170                 print output
171                 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:] ")))
172             primary_key = m.group(1)
173             primary_key = primary_key.replace(" ","")
174             if not ldap_fin_uid_id.has_key(primary_key):
175                 utils.warn("0x%s (from 0x%s): no UID found in LDAP" % (primary_key, fingerprint))
176             else:
177                 (uid, uid_id) = ldap_fin_uid_id[primary_key]
178                 q = projectB.query("UPDATE fingerprint SET uid = %s WHERE id = %s" % (uid_id, fingerprint_id))
179                 print "Assigning %s to 0x%s." % (uid, fingerprint)
180         else:
181             extra_keyrings = ""
182             for keyring in Cnf.ValueList("Import-LDAP-Fingerprints::ExtraKeyrings"):
183                 extra_keyrings += " --keyring=%s" % (keyring)
184             cmd = "gpg %s %s --list-key %s" \
185                   % (utils.gpg_keyring_args(), extra_keyrings, fingerprint)
186             (result, output) = commands.getstatusoutput(cmd)
187             if result != 0:
188                 cmd = "gpg --keyserver=%s --allow-non-selfsigned-uid --recv-key %s" % (Cnf["Import-LDAP-Fingerprints::KeyServer"], fingerprint)
189                 (result, output) = commands.getstatusoutput(cmd)
190                 if result != 0:
191                     print "0x%s: NOT found on keyserver." % (fingerprint)
192                     print cmd
193                     print result
194                     print output
195                     continue
196                 else:
197                     cmd = "gpg --list-key %s" % (fingerprint)
198                     (result, output) = commands.getstatusoutput(cmd)
199                     if result != 0:
200                         print "0x%s: --list-key returned error after --recv-key didn't." % (fingerprint)
201                         print cmd
202                         print result
203                         print output
204                         continue
205             m = re_debian_address.search(output)
206             if m:
207                 guess_uid = m.group(1)
208             else:
209                 guess_uid = "???"
210             name = " ".join(output.split('\n')[0].split()[3:])
211             print "0x%s -> %s -> %s" % (fingerprint, name, guess_uid)
212
213             # FIXME: make me optionally non-interactive
214             # FIXME: default to the guessed ID
215             uid = None
216             while not uid:
217                 uid = utils.our_raw_input("Map to which UID ? ")
218                 Attrs = l.search_s(LDAPDn,ldap.SCOPE_ONELEVEL,"(uid=%s)" % (uid), ["cn","mn","sn"])
219                 if not Attrs:
220                     print "That UID doesn't exist in LDAP!"
221                     uid = None
222                 else:
223                     entry = Attrs[0][1]
224                     name = get_ldap_name(entry)
225                     prompt = "Map to %s - %s (y/N) ? " % (uid, name.replace("  "," "))
226                     yn = utils.our_raw_input(prompt).lower()
227                     if yn == "y":
228                         uid_id = database.get_or_set_uid_id(uid)
229                         projectB.query("UPDATE fingerprint SET uid = %s WHERE id = %s" % (uid_id, fingerprint_id))
230                         print "Assigning %s to 0x%s." % (uid, fingerprint)
231                     else:
232                         uid = None
233     projectB.query("COMMIT WORK")
234
235 ############################################################
236
237 if __name__ == '__main__':
238     main()