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