Echelon
[mirror/userdir-ldap.git] / ud-gpgimport
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3 # This script tries to match key fingerprints from a keyring with user
4 # name in a directory. When an unassigned key is found a heuristic match
5 # against the keys given cn/sn and the directory is performed to try to get
6 # a matching. Generally this works about 90% of the time, matching is fairly
7 # strict. In the event a non-match a fuzzy sounds-alike search is performed
8 # and the results printed to aide the user.
9 #
10 # GPG is automatically invoked with the correct magic special options,
11 # pass the names of all the valid key rings on the command line.
12 #
13 # The output report will list what actions were taken. Keys that are present
14 # in the directory but not in the key ring will be removed from the 
15 # directory. 
16
17 import string, re, time, ldap, getopt, sys, pwd, posix;
18 from userdir_ldap import *;
19 from userdir_gpg import *;
20
21 # This map deals with people who put the wrong sort of stuff in their pgp
22 # key entries
23 UnknownMap = {};
24 NoAct = 1;
25
26 # Read the override file into the unknown map. The override file is a list
27 # of colon delimited entires mapping PGP email addresess to local users
28 def LoadOverride(File):
29    List = open(File,"r");
30    while(1):
31       Line = List.readline();
32       if Line == "":
33          break;
34       Split = re.split("[:\n]",Line);
35       UnknownMap[Split[0]] = string.strip(Split[1]);
36
37 # Convert the PGP name string to a uid value
38 def GetUID(l,Name):
39    # Crack up the email address into a best guess first/middle/last name
40    (cn,mn,sn) = NameSplit(re.sub('["]','',Name[0]))
41    
42    # Brackets anger the ldap searcher
43    cn = re.sub('[(")]','?',cn);
44    sn = re.sub('[(")]','?',sn);
45
46    # First check the unknown map for the email address
47    if UnknownMap.has_key(Name[1] + '@' + Name[2]):
48       print "unknown map hit for",Name;
49       return UnknownMap[Name[1] + '@' + Name[2]];
50
51    # Then the cruft component (ie there was no email address to match)
52    if UnknownMap.has_key(Name[2]):
53       print "unknown map hit for",Name;
54       return UnknownMap[Name[2]];
55
56    # Search for a possible first/last name hit
57    try:
58       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(&(cn=%s)(sn=%s))"%(cn,sn),["uid"]);
59    except ldap.FILTER_ERROR:
60       print "Filter failure:","(&(cn=%s)(sn=%s))"%(cn,sn);
61       return None;
62
63    # Hmm, more than one/no return
64    if (len(Attrs) != 1):
65       # Key claims a local address
66       if Name[2] == EmailAppend:
67
68          # Pull out the record for the claimed user
69          Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(uid=%s)"%(Name[1]),["uid","sn","cn"]);
70
71          # We require the UID surname to be someplace in the key name, this
72          # deals with special purpose keys like 'James Troup (Alternate Debian key)'
73          # Some people put their names backwards on their key too.. check that as well
74          if len(Attrs) == 1 and \
75             (string.find(string.lower(sn),string.lower(Attrs[0][1]["sn"][0])) != -1 or \
76             string.find(string.lower(cn),string.lower(Attrs[0][1]["sn"][0])) != -1):
77             print EmailAppend,"hit for",Name;
78             return Name[1];
79
80       # Attempt to give some best guess suggestions for use in editing the
81       # override file.
82       print "None for",Name;
83       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(sn~=%s)"%(sn),["uid","sn","cn"]);
84       for x in Attrs:
85          print "  But might be:",x[1]["cn"][0],x[1]["sn"][0],"<" + x[1]["uid"][0] + "@debian.org>";
86    else:
87       return Attrs[0][1]["uid"][0];
88
89    return None;
90
91 # Process options
92 AdminUser = pwd.getpwuid(posix.getuid())[0];
93 (options, arguments) = getopt.getopt(sys.argv[1:], "au:m:n")
94 for (switch, val) in options:
95    if (switch == '-u'):
96       AdminUser = val
97    elif (switch == '-m'):
98        LoadOverride(val);
99    elif (switch == '-a'):
100        NoAct = 0;
101 if len(arguments) == 0:
102    print "Give some keyrings to probe";
103    os.exit(0);
104
105 # Main program starts here
106
107 # Connect to the ldap server
108 l = ldap.open(LDAPServer);
109 if NoAct == 0:
110    print "Accessing LDAP directory as '" + AdminUser + "'";
111    Password = getpass(AdminUser + "'s password: ");
112    UserDn = "uid=" + AdminUser + "," + BaseDn;
113    l.simple_bind_s(UserDn,Password);
114 else:
115    l.simple_bind_s("","");
116
117 # Download the existing key list and put it into a map
118 print "Fetching key list..",
119 sys.stdout.flush();
120 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=*",["keyfingerprint","uid"]);
121 KeyMap = {};
122 KeyCount = {};
123 for x in Attrs:
124   try:
125      # Sense a bad fingerprint.. Slapd has problems, it will store a null
126      # value that ldapsearch doesn't show up.. detect and remove
127      if len(x[1]["keyfingerprint"]) == 0 or x[1]["keyfingerprint"][0] == "":
128        print;
129        print "Fixing bad fingerprint for",x[1]["uid"][0],
130        sys.stdout.flush();
131        if NoAct == 0:
132          l.modify_s("uid="+x[1]["uid"][0]+","+BaseDn,\
133                      [(ldap.MOD_DELETE,"keyfingerprint",None)]);
134      else:
135        for I in x[1]["keyfingerprint"]:
136          KeyMap[I] = [x[1]["uid"][0],0];
137          if KeyCount.has_key(x[1]["uid"][0]):
138             KeyCount[x[1]["uid"][0]] = KeyCount[x[1]["uid"][0]] + 1;
139          else:
140             KeyCount[x[1]["uid"][0]] = 1;
141   except:
142      continue;
143 Attrs = None;
144 print;
145
146 # Popen GPG with the correct magic special options
147 Args = [GPGPath] + GPGBasicOptions;
148 for x in arguments:
149    Args.append("--keyring");
150    if string.find(x,"/") == -1:
151       Args.append("./"+x);
152    else:
153       Args.append(x);
154 Args = Args + GPGSearchOptions + [" 2> /dev/null"]
155 Keys = os.popen(string.join(Args," "),"r");
156
157 # Loop over the GPG key file
158 Outstanding = 0;
159 Ignored = 0;
160 SeenKeys = {};
161 while(1):
162    Line = Keys.readline();
163    if Line == "":
164       break;
165    
166    Split = string.split(Line,":");
167    if len(Split) < 8 or Split[0] != "pub":
168       continue;
169
170    while (1):
171        Line2 = Keys.readline();
172        if Line2 == "":
173           break;
174        Split2 = string.split(Line2,":");
175        if len(Split2) < 11 or Split2[0] != "fpr":
176           continue;
177        break;
178    if Line2 == "":
179       break;
180
181    if SeenKeys.has_key(Split2[9]):
182       print "Dup key 0x",Split2[9],"belonging to",KeyMap[Split2[9]][0];
183       continue;
184    SeenKeys[Split2[9]] = None;
185
186    if KeyMap.has_key(Split2[9]):
187       Ignored = Ignored + 1;
188       # print "Ignoring keyID",Split2[9],"belonging to",KeyMap[Split2[9]][0];
189       KeyMap[Split2[9]][1] = 1;
190       continue;
191
192    Match = AddressSplit.match(Split[9]);
193    if Match == None:
194       UID = GetUID(l,("","",Split[9]));
195    else:
196       UID = GetUID(l,Match.groups());
197
198    if UID == None:
199       print "MISSING 0x" + Split2[9];
200       continue;
201
202    Rec = [(ldap.MOD_ADD,"keyfingerprint",Split2[9])];
203    Dn = "uid=" + UID + "," + BaseDn;
204    print "Adding key 0x"+Split2[9],"to",UID;
205    if KeyCount.has_key(UID):
206       KeyCount[UID] = KeyCount[UID] + 1;
207    else:
208       KeyCount[UID] = 1;
209    
210    if NoAct == 1:
211       continue;
212
213    # Send the modify request
214    l.modify(Dn,Rec);
215    Outstanding = Outstanding + 1;
216    Outstanding = FlushOutstanding(l,Outstanding,1);
217    sys.stdout.flush();
218
219 if NoAct == 0:
220    FlushOutstanding(l,Outstanding);
221
222 if Keys.close() != None:
223    raise "Error","GPG failed"
224
225 print Ignored,"keys already in the directory (ignored)";
226
227 # Look for unmatched keys
228 for x in KeyMap.keys():
229    if KeyMap[x][1] == 0:
230       print "key 0x",x,"belonging to",KeyMap[x][0],"removed";
231       if KeyCount.has_key(KeyMap[x][0]) :
232          KeyCount[KeyMap[x][0]] = KeyCount[KeyMap[x][0]] - 1
233          if KeyCount[KeyMap[x][0]] <= 0:
234             print "**",KeyMap[x][0],"no longer has any keys";
235       if NoAct == 0:
236          l.modify_s("uid="+KeyMap[x][0]+","+BaseDn,\
237                      [(ldap.MOD_DELETE,"keyfingerprint",x)]);
238