]> git.decadent.org.uk Git - dak.git/blob - dak/import_ldap_fingerprints.py
Enmasse adaptation for removal of silly names.
[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 import dak.lib.database, dak.lib.utils
50
51 ################################################################################
52
53 Cnf = None
54 projectB = None
55
56 re_gpg_fingerprint = re.compile(r"^\s+Key fingerprint = (.*)$", re.MULTILINE)
57 re_debian_address = re.compile(r"^.*<(.*)@debian\.org>$", re.MULTILINE)
58
59 ################################################################################
60
61 def usage(exit_code=0):
62     print """Usage: dak import-ldap-fingerprints
63 Syncs fingerprint and uid tables with a debian.org LDAP DB
64
65   -h, --help                show this help and exit."""
66     sys.exit(exit_code)
67
68 ################################################################################
69
70 def get_ldap_value(entry, value):
71     ret = entry.get(value)
72     if not ret:
73         return ""
74     else:
75         # FIXME: what about > 0 ?
76         return ret[0]
77
78 def main():
79     global Cnf, projectB
80
81     Cnf = dak.lib.utils.get_conf()
82     Arguments = [('h',"help","Import-LDAP-Fingerprints::Options::Help")]
83     for i in [ "help" ]:
84         if not Cnf.has_key("Import-LDAP-Fingerprints::Options::%s" % (i)):
85             Cnf["Import-LDAP-Fingerprints::Options::%s" % (i)] = ""
86
87     apt_pkg.ParseCommandLine(Cnf, Arguments, sys.argv)
88
89     Options = Cnf.SubTree("Import-LDAP-Fingerprints::Options")
90     if Options["Help"]:
91         usage()
92
93     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
94     dak.lib.database.init(Cnf, projectB)
95
96     LDAPDn = Cnf["Import-LDAP-Fingerprints::LDAPDn"]
97     LDAPServer = Cnf["Import-LDAP-Fingerprints::LDAPServer"]
98     l = ldap.open(LDAPServer)
99     l.simple_bind_s("","")
100     Attrs = l.search_s(LDAPDn, ldap.SCOPE_ONELEVEL,
101                        "(&(keyfingerprint=*)(gidnumber=%s))" % (Cnf["Import-Users-From-Passwd::ValidGID"]),
102                        ["uid", "keyfingerprint"])
103
104
105     projectB.query("BEGIN WORK")
106
107
108     # Sync LDAP with DB
109     db_fin_uid = {}
110     ldap_fin_uid_id = {}
111     q = projectB.query("""
112 SELECT f.fingerprint, f.id, u.uid FROM fingerprint f, uid u WHERE f.uid = u.id
113  UNION SELECT f.fingerprint, f.id, null FROM fingerprint f where f.uid is null""")
114     for i in q.getresult():
115         (fingerprint, fingerprint_id, uid) = i
116         db_fin_uid[fingerprint] = (uid, fingerprint_id)
117
118     for i in Attrs:
119         entry = i[1]
120         fingerprints = entry["keyFingerPrint"]
121         uid = entry["uid"][0]
122         uid_id = dak.lib.database.get_or_set_uid_id(uid)
123         for fingerprint in fingerprints:
124             ldap_fin_uid_id[fingerprint] = (uid, uid_id)
125             if db_fin_uid.has_key(fingerprint):
126                 (existing_uid, fingerprint_id) = db_fin_uid[fingerprint]
127                 if not existing_uid:
128                     q = projectB.query("UPDATE fingerprint SET uid = %s WHERE id = %s" % (uid_id, fingerprint_id))
129                     print "Assigning %s to 0x%s." % (uid, fingerprint)
130                 else:
131                     if existing_uid != uid:
132                         dak.lib.utils.fubar("%s has %s in LDAP, but projectB says it should be %s." % (uid, fingerprint, existing_uid))
133
134     # Try to update people who sign with non-primary key
135     q = projectB.query("SELECT fingerprint, id FROM fingerprint WHERE uid is null")
136     for i in q.getresult():
137         (fingerprint, fingerprint_id) = i
138         cmd = "gpg --no-default-keyring --keyring=%s --keyring=%s --fingerprint %s" \
139               % (Cnf["Dinstall::PGPKeyring"], Cnf["Dinstall::GPGKeyring"],
140                  fingerprint)
141         (result, output) = commands.getstatusoutput(cmd)
142         if result == 0:
143             m = re_gpg_fingerprint.search(output)
144             if not m:
145                 print output
146                 dak.lib.utils.fubar("0x%s: No fingerprint found in gpg output but it returned 0?\n%s" % (fingerprint, dak.lib.utils.prefix_multi_line_string(output, " [GPG output:] ")))
147             primary_key = m.group(1)
148             primary_key = primary_key.replace(" ","")
149             if not ldap_fin_uid_id.has_key(primary_key):
150                 dak.lib.utils.fubar("0x%s (from 0x%s): no UID found in LDAP" % (primary_key, fingerprint))
151             (uid, uid_id) = ldap_fin_uid_id[primary_key]
152             q = projectB.query("UPDATE fingerprint SET uid = %s WHERE id = %s" % (uid_id, fingerprint_id))
153             print "Assigning %s to 0x%s." % (uid, fingerprint)
154         else:
155             extra_keyrings = ""
156             for keyring in Cnf.ValueList("Import-LDAP-Fingerprints::ExtraKeyrings"):
157                 extra_keyrings += " --keyring=%s" % (keyring)
158             cmd = "gpg --keyring=%s --keyring=%s %s --list-key %s" \
159                   % (Cnf["Dinstall::PGPKeyring"], Cnf["Dinstall::GPGKeyring"],
160                      extra_keyrings, fingerprint)
161             (result, output) = commands.getstatusoutput(cmd)
162             if result != 0:
163                 cmd = "gpg --keyserver=%s --allow-non-selfsigned-uid --recv-key %s" % (Cnf["Import-LDAP-Fingerprints::KeyServer"], fingerprint)
164                 (result, output) = commands.getstatusoutput(cmd)
165                 if result != 0:
166                     print "0x%s: NOT found on keyserver." % (fingerprint)
167                     print cmd
168                     print result
169                     print output
170                     continue
171                 else:
172                     cmd = "gpg --list-key %s" % (fingerprint)
173                     (result, output) = commands.getstatusoutput(cmd)
174                     if result != 0:
175                         print "0x%s: --list-key returned error after --recv-key didn't." % (fingerprint)
176                         print cmd
177                         print result
178                         print output
179                         continue
180             m = re_debian_address.search(output)
181             if m:
182                 guess_uid = m.group(1)
183             else:
184                 guess_uid = "???"
185             name = " ".join(output.split('\n')[0].split()[3:])
186             print "0x%s -> %s -> %s" % (fingerprint, name, guess_uid)
187             # FIXME: make me optionally non-interactive
188             # FIXME: default to the guessed ID
189             uid = None
190             while not uid:
191                 uid = dak.lib.utils.our_raw_input("Map to which UID ? ")
192                 Attrs = l.search_s(LDAPDn,ldap.SCOPE_ONELEVEL,"(uid=%s)" % (uid), ["cn","mn","sn"])
193                 if not Attrs:
194                     print "That UID doesn't exist in LDAP!"
195                     uid = None
196                 else:
197                     entry = Attrs[0][1]
198                     name = " ".join([get_ldap_value(entry, "cn"),
199                                      get_ldap_value(entry, "mn"),
200                                      get_ldap_value(entry, "sn")])
201                     prompt = "Map to %s - %s (y/N) ? " % (uid, name.replace("  "," "))
202                     yn = dak.lib.utils.our_raw_input(prompt).lower()
203                     if yn == "y":
204                         uid_id = dak.lib.database.get_or_set_uid_id(uid)
205                         projectB.query("UPDATE fingerprint SET uid = %s WHERE id = %s" % (uid_id, fingerprint_id))
206                         print "Assigning %s to 0x%s." % (uid, fingerprint)
207                     else:
208                         uid = None
209     projectB.query("COMMIT WORK")
210
211 ############################################################
212
213 if __name__ == '__main__':
214     main()