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