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