ud-gpgimport: handle guest keyrings
[mirror/userdir-ldap.git] / ud-gpgimport
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3
4 #   Copyright (c) 1999-2000  Jason Gunthorpe <jgg@debian.org>
5 #   Copyright (c) 2004       Joey Schulze <joey@debian.org>
6 #   Copyright (c) 2008, 2009, 2010 Peter Palfrader <peter@palfrader.org>
7 #
8 #   This program is free software; you can redistribute it and/or modify
9 #   it under the terms of the GNU General Public License as published by
10 #   the Free Software Foundation; either version 2 of the License, or
11 #   (at your option) any later version.
12 #
13 #   This program is distributed in the hope that it will be useful,
14 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #   GNU General Public License for more details.
17 #
18 #   You should have received a copy of the GNU General Public License
19 #   along with this program; if not, write to the Free Software
20 #   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21
22 # This script tries to match key fingerprints from a keyring with user
23 # name in a directory. When an unassigned key is found a heuristic match
24 # against the keys given cn/sn and the directory is performed to try to get
25 # a matching. Generally this works about 90% of the time, matching is fairly
26 # strict. In the event a non-match a fuzzy sounds-alike search is performed
27 # and the results printed to aide the user.
28 #
29 # GPG is automatically invoked with the correct magic special options,
30 # pass the names of all the valid key rings on the command line.
31 #
32 # The output report will list what actions were taken. Keys that are present
33 # in the directory but not in the key ring will be removed from the 
34 # directory. 
35
36 import re, time, ldap, getopt, sys, pwd, os;
37 from userdir_ldap import *;
38 from userdir_gpg import *;
39
40 # This map deals with people who put the wrong sort of stuff in their pgp
41 # key entries
42 UnknownMap = {};
43 NoAct = 1;
44
45 # Read the override file into the unknown map. The override file is a list
46 # of colon delimited entires mapping PGP email addresess to local users
47 def LoadOverride(File):
48    List = open(File,"r");
49    while(1):
50       Line = List.readline();
51       if Line == "":
52          break;
53       Split = re.split("[:\n]",Line);
54       UnknownMap[Split[0]] = Split[1].strip()
55
56
57 def load_keys_from_gpg(keyrings):
58    keys = {}
59
60    # Popen GPG with the correct magic special options
61    ClearKeyrings()
62    SetKeyrings(keyrings)
63
64    Args = [GPGPath] + GPGBasicOptions + GPGKeyRings + GPGSearchOptions + [" 2> /dev/null"]
65    Keys = os.popen(" ".join(Args),"r");
66
67    # Loop over the GPG key file
68    Outstanding = 0;
69    while(1):
70       Line = Keys.readline();
71       if Line == "":
72          break;
73
74       Split = Line.split(":")
75       if len(Split) < 8 or Split[0] != "pub":
76          continue;
77
78       while (1):
79           Line2 = Keys.readline();
80           if Line2 == "":
81              break;
82           Split2 = Line2.split(":");
83           if len(Split2) < 11 or Split2[0] != "fpr":
84              continue;
85           break;
86       if Line2 == "":
87          break;
88
89       pgp_uid = Split[9]
90       fingerprint = Split2[9]
91
92       if fingerprint in keys:
93          print "Duplicate key in keyrings: %s, belonging to %s"%(fingerprint, pgp_uid)
94          continue
95       keys[fingerprint] = pgp_uid
96
97    if Keys.close() != None:
98       raise "Error","GPG failed"
99
100    return keys
101
102
103
104
105
106
107 # Process options
108 AdminUser = pwd.getpwuid(os.getuid())[0];
109 (options, arguments) = getopt.getopt(sys.argv[1:], "au:m:n")
110 for (switch, val) in options:
111    if (switch == '-u'):
112       AdminUser = val
113    elif (switch == '-m'):
114        LoadOverride(val);
115    elif (switch == '-a'):
116        NoAct = 0;
117
118
119 # Main program starts here
120
121 # Connect to the ldap server
122 if NoAct == 0:
123    l = passwdAccessLDAP(BaseDn, AdminUser)
124 else:
125    l = connectLDAP()
126    l.simple_bind_s("","");
127
128 # Download the existing key list and put it into a map
129 print "Fetching key list..",
130 sys.stdout.flush();
131 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=*",["keyFingerPrint","uid"]);
132 KeyMap = {};
133 KeyCount = {};
134 for x in Attrs:
135   try:
136      # Sense a bad fingerprint.. Slapd has problems, it will store a null
137      # value that ldapsearch doesn't show up.. detect and remove
138      if len(x[1]["keyFingerPrint"]) == 0 or x[1]["keyFingerPrint"][0] == "":
139        print;
140        print "Fixing bad fingerprint for",x[1]["uid"][0],
141        sys.stdout.flush();
142        if NoAct == 0:
143          l.modify_s("uid="+x[1]["uid"][0]+","+BaseDn,\
144                      [(ldap.MOD_DELETE,"keyFingerPrint",None)]);
145      else:
146        for I in x[1]["keyFingerPrint"]:
147          KeyMap[I] = [x[1]["uid"][0],0];
148          if KeyCount.has_key(x[1]["uid"][0]):
149             KeyCount[x[1]["uid"][0]] = KeyCount[x[1]["uid"][0]] + 1;
150          else:
151             KeyCount[x[1]["uid"][0]] = 1;
152   except:
153      continue;
154 Attrs = None;
155 print;
156
157
158 pgpkeys = load_keys_from_gpg( ConfModule.add_keyrings.split(":") )
159 pgpkeys_extra = load_keys_from_gpg( ConfModule.add_keyrings_guest.split(":") )
160
161 Ignored = 0;
162 for fpr in pgpkeys:
163    pgp_uid = pgpkeys[fpr]
164    if fpr in KeyMap:
165       Ignored = Ignored + 1;
166       # print "Ignoring keyID",fpr,"belonging to",KeyMap[fpr][0];
167       KeyMap[fpr][1] = 1;
168       continue;
169
170    UID = GetUID(l,SplitEmail(pgp_uid),UnknownMap);
171    if UID[0] == None:
172       print "Unassigned key in keyrings: %s, belonging to %s"%(fpr, pgp_uid)
173       if UID[1] != None:
174          for x in UID[1]: print x;
175       print "MISSING " + fpr;
176       continue;
177
178    UID = UID[0]
179    Rec = [(ldap.MOD_ADD,"keyFingerPrint",fpr)];
180    Dn = "uid=" + UID + "," + BaseDn;
181    print "Adding key "+fpr,"to",UID;
182    if KeyCount.has_key(UID):
183       KeyCount[UID] = KeyCount[UID] + 1;
184    else:
185       KeyCount[UID] = 1;
186
187    if NoAct == 1:
188       continue;
189
190    # Send the modify request
191    l.modify(Dn,Rec);
192    Outstanding = Outstanding + 1;
193    Outstanding = FlushOutstanding(l,Outstanding,1);
194    sys.stdout.flush();
195
196 if NoAct == 0:
197    FlushOutstanding(l,Outstanding);
198
199 print Ignored,"keys already in the directory (ignored)";
200
201 # Look for unmatched keys
202 for x in KeyMap.keys():
203    if KeyMap[x][1] == 0 and not x in pgpkeys_extra:
204       print "key %s belonging to %s removed"%(x,KeyMap[x][0]);
205       if KeyCount.has_key(KeyMap[x][0]) :
206          KeyCount[KeyMap[x][0]] = KeyCount[KeyMap[x][0]] - 1
207          if KeyCount[KeyMap[x][0]] <= 0:
208             print "**",KeyMap[x][0],"no longer has any keys";
209       if NoAct == 0:
210          l.modify_s("uid="+KeyMap[x][0]+","+BaseDn,\
211                      [(ldap.MOD_DELETE,"keyFingerPrint",x)]);
212
213 # vim:set et:
214 # vim:set ts=3:
215 # vim:set shiftwidth=3: