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