Use the common routine from userdir_ldap.py which asks for the
[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, os;
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 # Process options
38 AdminUser = pwd.getpwuid(os.getuid())[0];
39 (options, arguments) = getopt.getopt(sys.argv[1:], "au:m:n")
40 for (switch, val) in options:
41    if (switch == '-u'):
42       AdminUser = val
43    elif (switch == '-m'):
44        LoadOverride(val);
45    elif (switch == '-a'):
46        NoAct = 0;
47 if len(arguments) == 0:
48    print "Give some keyrings to probe";
49    sys.exit(0);
50
51 # Main program starts here
52
53 # Connect to the ldap server
54 if NoAct == 0:
55    l = passwdAccessLDAP(LDAPServer, BaseDn, AdminUser)
56 else:
57    l = ldap.open(LDAPServer);
58    l.simple_bind_s("","");
59
60 # Download the existing key list and put it into a map
61 print "Fetching key list..",
62 sys.stdout.flush();
63 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=*",["keyFingerPrint","uid"]);
64 KeyMap = {};
65 KeyCount = {};
66 for x in Attrs:
67   try:
68      # Sense a bad fingerprint.. Slapd has problems, it will store a null
69      # value that ldapsearch doesn't show up.. detect and remove
70      if len(x[1]["keyFingerPrint"]) == 0 or x[1]["keyFingerPrint"][0] == "":
71        print;
72        print "Fixing bad fingerprint for",x[1]["uid"][0],
73        sys.stdout.flush();
74        if NoAct == 0:
75          l.modify_s("uid="+x[1]["uid"][0]+","+BaseDn,\
76                      [(ldap.MOD_DELETE,"keyFingerPrint",None)]);
77      else:
78        for I in x[1]["keyFingerPrint"]:
79          KeyMap[I] = [x[1]["uid"][0],0];
80          if KeyCount.has_key(x[1]["uid"][0]):
81             KeyCount[x[1]["uid"][0]] = KeyCount[x[1]["uid"][0]] + 1;
82          else:
83             KeyCount[x[1]["uid"][0]] = 1;
84   except:
85      continue;
86 Attrs = None;
87 print;
88
89 # Popen GPG with the correct magic special options
90 Args = [GPGPath] + GPGBasicOptions;
91 for x in arguments:
92    Args.append("--keyring");
93    if string.find(x,"/") == -1:
94       Args.append("./"+x);
95    else:
96       Args.append(x);
97 Args = Args + GPGSearchOptions + [" 2> /dev/null"]
98 Keys = os.popen(string.join(Args," "),"r");
99
100 # Loop over the GPG key file
101 Outstanding = 0;
102 Ignored = 0;
103 SeenKeys = {};
104 while(1):
105    Line = Keys.readline();
106    if Line == "":
107       break;
108    
109    Split = string.split(Line,":");
110    if len(Split) < 8 or Split[0] != "pub":
111       continue;
112
113    while (1):
114        Line2 = Keys.readline();
115        if Line2 == "":
116           break;
117        Split2 = string.split(Line2,":");
118        if len(Split2) < 11 or Split2[0] != "fpr":
119           continue;
120        break;
121    if Line2 == "":
122       break;
123
124    if SeenKeys.has_key(Split2[9]):
125       print "Dup key 0x",Split2[9],"belonging to",KeyMap[Split2[9]][0];
126       continue;
127    SeenKeys[Split2[9]] = None;
128
129    if KeyMap.has_key(Split2[9]):
130       Ignored = Ignored + 1;
131       # print "Ignoring keyID",Split2[9],"belonging to",KeyMap[Split2[9]][0];
132       KeyMap[Split2[9]][1] = 1;
133       continue;
134       
135    UID = GetUID(l,SplitEmail(Split[9]),UnknownMap);
136    if UID[0] == None:
137       print "None for",SplitEmail(Split[9]),"'%s'"%(Split[9]);
138       if UID[1] != None: 
139          for x in UID[1]: print x;
140       print "MISSING 0x" + Split2[9];
141       continue;
142
143    UID = UID[0]
144    Rec = [(ldap.MOD_ADD,"keyFingerPrint",Split2[9])];
145    Dn = "uid=" + UID + "," + BaseDn;
146    print "Adding key 0x"+Split2[9],"to",UID;
147    if KeyCount.has_key(UID):
148       KeyCount[UID] = KeyCount[UID] + 1;
149    else:
150       KeyCount[UID] = 1;
151    
152    if NoAct == 1:
153       continue;
154
155    # Send the modify request
156    l.modify(Dn,Rec);
157    Outstanding = Outstanding + 1;
158    Outstanding = FlushOutstanding(l,Outstanding,1);
159    sys.stdout.flush();
160
161 if NoAct == 0:
162    FlushOutstanding(l,Outstanding);
163
164 if Keys.close() != None:
165    raise "Error","GPG failed"
166
167 print Ignored,"keys already in the directory (ignored)";
168
169 # Look for unmatched keys
170 for x in KeyMap.keys():
171    if KeyMap[x][1] == 0:
172       print "key 0x%s belonging to %s removed"%(x,KeyMap[x][0]);
173       if KeyCount.has_key(KeyMap[x][0]) :
174          KeyCount[KeyMap[x][0]] = KeyCount[KeyMap[x][0]] - 1
175          if KeyCount[KeyMap[x][0]] <= 0:
176             print "**",KeyMap[x][0],"no longer has any keys";
177       if NoAct == 0:
178          l.modify_s("uid="+KeyMap[x][0]+","+BaseDn,\
179                      [(ldap.MOD_DELETE,"keyFingerPrint",x)]);
180