Do SSL when connecting to the ldap server.
[mirror/userdir-ldap.git] / ud-generate
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3 # Generates passwd, shadow and group files from the ldap directory.
4
5 #   Copyright (c) 2000-2001  Jason Gunthorpe <jgg@debian.org>
6 #   Copyright (c) 2003-2004  James Troup <troup@debian.org>
7 #   Copyright (c) 2004-2005,7  Joey Schulze <joey@infodrom.org>
8 #   Copyright (c) 2001-2007  Ryan Murray <rmurray@debian.org>
9 #   Copyright (c) 2008 Peter Palfrader <peter@palfrader.org>
10 #   Copyright (c) 2008 Andreas Barth <aba@not.so.argh.org>
11 #   Copyright (c) 2008 Mark Hymers <mhy@debian.org>
12 #
13 #   This program is free software; you can redistribute it and/or modify
14 #   it under the terms of the GNU General Public License as published by
15 #   the Free Software Foundation; either version 2 of the License, or
16 #   (at your option) any later version.
17 #
18 #   This program is distributed in the hope that it will be useful,
19 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
20 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 #   GNU General Public License for more details.
22 #
23 #   You should have received a copy of the GNU General Public License
24 #   along with this program; if not, write to the Free Software
25 #   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26
27 import string, re, time, ldap, getopt, sys, os, pwd, posix, socket, base64, sha, shutil, errno, tarfile, grp
28 from userdir_ldap import *;
29
30 global Allowed;
31 global CurrentHost;
32
33 PasswdAttrs = None;
34 GroupIDMap = {};
35 Allowed = None;
36 CurrentHost = "";
37
38 EmailCheck = re.compile("^([^ <>@]+@[^ ,<>@]+)?$");
39 BSMTPCheck = re.compile(".*mx 0 (gluck)\.debian\.org\..*",re.DOTALL);
40 DNSZone = ".debian.net"
41 Keyrings = ConfModule.sync_keyrings.split(":")
42
43 def safe_makedirs(dir):
44     try:
45         os.makedirs(dir)
46     except OSError, e:
47         if e.errno == errno.EEXIST:
48             pass
49         else:
50             raise e
51
52 def safe_rmtree(dir):
53     try:
54         shutil.rmtree(dir)
55     except OSError, e:
56         if e.errno == errno.ENOENT:
57             pass
58         else:
59             raise e
60
61 def Sanitize(Str):
62   return Str.translate(string.maketrans("\n\r\t","$$$"))
63
64 def DoLink(From,To,File):
65    try: posix.remove(To+File);
66    except: pass;
67    posix.link(From+File,To+File);
68
69 # See if this user is in the group list
70 def IsInGroup(DnRecord):
71   if Allowed == None:
72      return 1;
73
74   # See if the primary group is in the list
75   if Allowed.has_key(GetAttr(DnRecord,"gidNumber")) != 0:
76      return 1;
77
78   # Check the host based ACL
79   if DnRecord[1].has_key("allowedHost") != 0:
80      for I in DnRecord[1]["allowedHost"]:
81         if CurrentHost == I:
82            return 1;
83
84   # See if there are supplementary groups
85   if DnRecord[1].has_key("supplementaryGid") == 0:
86      return 0;
87
88   # Check the supplementary groups
89   for I in DnRecord[1]["supplementaryGid"]:
90      if Allowed.has_key(I):
91         return 1;
92   return 0;
93
94 def Die(File,F,Fdb):
95    if F != None:
96       F.close();
97    if Fdb != None:
98       Fdb.close();
99    try: os.remove(File + ".tmp");
100    except: pass;
101    try: os.remove(File + ".tdb.tmp");
102    except: pass;
103
104 def Done(File,F,Fdb):
105   if F != None:
106     F.close();
107     os.rename(File + ".tmp",File);
108   if Fdb != None:
109     Fdb.close();
110     os.rename(File + ".tdb.tmp",File+".tdb");
111   
112 # Generate the password list
113 def GenPasswd(l,File,HomePrefix,PwdMarker):
114   F = None;
115   try:
116    F = open(File + ".tdb.tmp","w");
117
118    userlist = {}
119    # Fetch all the users
120    global PasswdAttrs;
121    if PasswdAttrs == None:
122       raise "No Users";
123
124    I = 0;
125    for x in PasswdAttrs:
126       if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
127          continue;
128
129       # Do not let people try to buffer overflow some busted passwd parser.
130       if len(GetAttr(x,"gecos")) > 100 or len(GetAttr(x,"loginShell")) > 50:
131          continue;
132
133       userlist[GetAttr(x, "uid")] = int(GetAttr(x, "gidNumber"))
134       Line = "%s:%s:%s:%s:%s:%s%s:%s" % (GetAttr(x,"uid"),\
135               PwdMarker,\
136               GetAttr(x,"uidNumber"),GetAttr(x,"gidNumber"),\
137               GetAttr(x,"gecos"),HomePrefix,GetAttr(x,"uid"),\
138               GetAttr(x,"loginShell"));
139
140       Line = Sanitize(Line) + "\n";
141       F.write("0%u %s" % (I,Line));
142       F.write(".%s %s" % (GetAttr(x,"uid"),Line));
143       F.write("=%s %s" % (GetAttr(x,"uidNumber"),Line));
144       I = I + 1;
145
146   # Oops, something unspeakable happened.
147   except:
148    Die(File,None,F);
149    raise;
150   Done(File,None,F);
151
152   # Return the list of users so we know which keys to export
153   return userlist
154
155 # Generate the shadow list
156 def GenShadow(l,File):
157   F = None;
158   try:
159    OldMask = os.umask(0077);
160    F = open(File + ".tdb.tmp","w",0600);
161    os.umask(OldMask);
162
163    # Fetch all the users
164    global PasswdAttrs;
165    if PasswdAttrs == None:
166       raise "No Users";
167
168    I = 0;
169    for x in PasswdAttrs:
170       if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
171          continue;
172          
173       Pass = GetAttr(x,"userPassword");
174       if Pass[0:7] != "{crypt}" or len(Pass) > 50:
175          Pass = '*';
176       else:
177          Pass = Pass[7:];
178
179       # If the account is locked, mark it as such in shadow
180       # See Debian Bug #308229 for why we set it to 1 instead of 0
181       if (GetAttr(x,"userPassword").find("*LK*") != -1) \
182           or GetAttr(x,"userPassword").startswith("!"):
183          ShadowExpire = '1'
184       else:
185          ShadowExpire = GetAttr(x,"shadowExpire")
186
187       Line = "%s:%s:%s:%s:%s:%s:%s:%s:" % (GetAttr(x,"uid"),\
188               Pass,GetAttr(x,"shadowLastChange"),\
189               GetAttr(x,"shadowMin"),GetAttr(x,"shadowMax"),\
190               GetAttr(x,"shadowWarning"),GetAttr(x,"shadowInactive"),\
191               ShadowExpire);
192       Line = Sanitize(Line) + "\n";
193       F.write("0%u %s" % (I,Line));
194       F.write(".%s %s" % (GetAttr(x,"uid"),Line));
195       I = I + 1;
196
197   # Oops, something unspeakable happened.
198   except:
199    Die(File,None,F);
200    raise;
201   Done(File,None,F);
202
203 # Generate the shadow list
204 def GenSSHShadow(l,masterFileName):
205    # Fetch all the users
206    singlefile = None
207    userfiles = []
208    # Depending on config, we write out either a single file,
209    # multiple files, or both
210    if SingleSSHFile:
211        try:
212            OldMask = os.umask(0077);
213            masterFile = open(masterFileName + ".tmp","w",0600);
214            os.umask(OldMask);
215        except IOError:
216            Die(masterFileName,masterFile,None)
217            raise
218
219    global PasswdAttrs;
220    if PasswdAttrs == None:
221       raise "No Users";
222
223    # If we're going to be dealing with multiple keys, empty the
224    # directory before we start to avoid old keys hanging around
225    if MultipleSSHFiles:
226       safe_rmtree(os.path.join(GlobalDir, 'userkeys'))
227       safe_makedirs(os.path.join(GlobalDir, 'userkeys'))
228       
229    for x in PasswdAttrs:
230       # If the account is locked, do not write it.
231       # This is a partial stop-gap. The ssh also needs to change this
232       # to ignore ~/.ssh/authorized* files.
233       if (GetAttr(x,"userPassword").find("*LK*") != -1) \
234              or GetAttr(x,"userPassword").startswith("!"):
235          continue;
236
237       if x[1].has_key("uidNumber") == 0 or \
238          x[1].has_key("sshRSAAuthKey") == 0:
239          continue;
240       User = GetAttr(x,"uid");
241       F = None;
242
243       try:
244          if MultipleSSHFiles:
245              OldMask = os.umask(0077);
246              File = os.path.join(GlobalDir, 'userkeys', User)
247              F = open(File + ".tmp","w",0600);
248              os.umask(OldMask);
249
250          for I in x[1]["sshRSAAuthKey"]:
251              if MultipleSSHFiles:
252                  MultipleLine = "%s" % I
253                  MultipleLine = Sanitize(MultipleLine) + "\n"
254                  F.write(MultipleLine)
255              if SingleSSHFile:
256                  SingleLine = "%s: %s" % (User, I)
257                  SingleLine = Sanitize(SingleLine) + "\n"
258                  masterFile.write(SingleLine)
259
260          if MultipleSSHFiles:
261              Done(File,F,None);
262              userfiles.append(os.path.basename(File))
263
264       # Oops, something unspeakable happened.
265       except IOError:
266           Die(File,F,None)
267           Die(masterFileName,masterFile,None)
268           raise;
269
270    if SingleSSHFile:
271        Done(masterFileName,masterFile,None)
272        singlefile = os.path.basename(masterFileName)
273
274    return singlefile, userfiles
275
276 # Generate the group list
277 def GenGroup(l,File):
278   grouprevmap = {}
279   F = None;
280   try:
281    F = open(File + ".tdb.tmp","w");
282
283    # Generate the GroupMap
284    GroupMap = {};
285    for x in GroupIDMap.keys():
286       GroupMap[x] = [];
287       
288    # Fetch all the users
289    global PasswdAttrs;
290    if PasswdAttrs == None:
291       raise "No Users";
292
293    # Sort them into a list of groups having a set of users
294    for x in PasswdAttrs:
295       if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
296          continue;
297       if x[1].has_key("supplementaryGid") == 0:
298          continue;
299          
300       for I in x[1]["supplementaryGid"]:
301          if GroupMap.has_key(I):
302             GroupMap[I].append(GetAttr(x,"uid"));
303          else:
304             print "Group does not exist ",I,"but",GetAttr(x,"uid"),"is in it";
305             
306    # Output the group file.
307    J = 0;
308    for x in GroupMap.keys():
309       grouprevmap[GroupIDMap[x]] = x
310       if GroupIDMap.has_key(x) == 0:
311          continue;
312       Line = "%s:x:%u:" % (x,GroupIDMap[x]);
313       Comma = '';
314       for I in GroupMap[x]:
315         Line = Line + ("%s%s" % (Comma,I));
316         Comma = ',';
317       Line = Sanitize(Line) + "\n";
318       F.write("0%u %s" % (J,Line));
319       F.write(".%s %s" % (x,Line));
320       F.write("=%u %s" % (GroupIDMap[x],Line));
321       J = J + 1;
322       
323   # Oops, something unspeakable happened.
324   except:
325    Die(File,None,F);
326    raise;
327   Done(File,None,F);
328
329   return grouprevmap
330
331 # Generate the email forwarding list
332 def GenForward(l,File):
333   F = None;
334   try:
335    OldMask = os.umask(0022);
336    F = open(File + ".tmp","w",0644);
337    os.umask(OldMask);
338
339    # Fetch all the users
340    global PasswdAttrs;
341    if PasswdAttrs == None:
342       raise "No Users";
343
344    # Write out the email address for each user
345    for x in PasswdAttrs:
346       if x[1].has_key("emailForward") == 0 or IsInGroup(x) == 0:
347          continue;
348       
349       # Do not allow people to try to buffer overflow busted parsers
350       if len(GetAttr(x,"emailForward")) > 200:
351          continue;
352
353       # Check the forwarding address
354       if EmailCheck.match(GetAttr(x,"emailForward")) == None:
355          continue;
356       Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailForward"));
357       Line = Sanitize(Line) + "\n";
358       F.write(Line);
359       
360   # Oops, something unspeakable happened.
361   except:
362    Die(File,F,None);
363    raise;
364   Done(File,F,None);
365
366 def GenAllForward(l,File):
367   Fdb = None;
368   try:
369    OldMask = os.umask(0022);
370    Fdb = os.popen("cdbmake %s %s.tmp"%(File,File),"w");
371    os.umask(OldMask);
372
373    # Fetch all the users
374    global PasswdAttrs;
375    if PasswdAttrs == None:
376       raise "No Users";
377
378    # Write out the email address for each user
379    for x in PasswdAttrs:
380       if x[1].has_key("emailForward") == 0:
381          continue;
382       
383       # Do not allow people to try to buffer overflow busted parsers
384       Forward = GetAttr(x,"emailForward");
385       if len(Forward) > 200:
386          continue;
387
388       # Check the forwarding address
389       if EmailCheck.match(Forward) == None:
390          continue;
391          
392       User = GetAttr(x,"uid");
393       Fdb.write("+%d,%d:%s->%s\n"%(len(User),len(Forward),User,Forward));
394    Fdb.write("\n");
395   # Oops, something unspeakable happened.
396   except:
397     Fdb.close();
398     raise;
399   if Fdb.close() != None:
400     raise "cdbmake gave an error";
401
402 # Generate the anon XEarth marker file 
403 def GenMarkers(l,File):
404   F = None;
405   try:
406    F = open(File + ".tmp","w");
407
408    # Fetch all the users
409    global PasswdAttrs;
410    if PasswdAttrs == None:
411       raise "No Users";
412
413    # Write out the position for each user
414    for x in PasswdAttrs:
415       if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
416          continue;       
417       try:
418          Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
419          Line = Sanitize(Line) + "\n";
420          F.write(Line);
421       except:
422          pass;
423       
424   # Oops, something unspeakable happened.
425   except:
426    Die(File,F,None);
427    raise;
428   Done(File,F,None);
429
430 # Generate the debian-private subscription list
431 def GenPrivate(l,File):
432   F = None;
433   try:
434    F = open(File + ".tmp","w");
435
436    # Fetch all the users
437    global PasswdAttrs;
438    if PasswdAttrs == None:
439       raise "No Users";
440
441    # Write out the position for each user
442    for x in PasswdAttrs:
443       if x[1].has_key("privateSub") == 0:
444          continue;
445
446       # If the account is locked, do not write it
447       if (GetAttr(x,"userPassword").find("*LK*") != -1) \
448              or GetAttr(x,"userPassword").startswith("!"):
449          continue;
450
451       # If the account has no PGP key, do not write it
452       if x[1].has_key("keyFingerPrint") == 0:
453          continue;
454
455       # Must be in the Debian group (yuk, hard coded for now)
456       if GetAttr(x,"gidNumber") != "800":
457          continue;
458
459       try:
460          Line = "%s"%(GetAttr(x,"privateSub"));
461          Line = Sanitize(Line) + "\n";
462          F.write(Line);
463       except:
464          pass;
465       
466   # Oops, something unspeakable happened.
467   except:
468    Die(File,F,None);
469    raise;
470   Done(File,F,None);
471
472 # Generate a list of locked accounts
473 def GenDisabledAccounts(l,File):
474   F = None;
475   try:
476    F = open(File + ".tmp","w");
477
478    # Fetch all the users
479    global PasswdAttrs;
480    if PasswdAttrs == None:
481       raise "No Users";
482
483    I = 0;
484    for x in PasswdAttrs:
485       if x[1].has_key("uidNumber") == 0:
486          continue;
487          
488       Pass = GetAttr(x,"userPassword");
489       Line = ""
490       # *LK* is the reference value for a locked account
491       # password starting with ! is also a locked account
492       if Pass.find("*LK*") != -1 or Pass.startswith("!"):
493          # Format is <login>:<reason>
494          Line = "%s:%s" % (GetAttr(x,"uid"), "Account is locked")
495
496       if Line != "":
497          F.write(Sanitize(Line) + "\n")
498
499   # Oops, something unspeakable happened.
500   except:
501    Die(File,F,None);
502    raise;
503   Done(File,F,None);
504
505 # Generate the list of local addresses that refuse all mail
506 def GenMailDisable(l,File):
507   F = None;
508   try:
509    F = open(File + ".tmp","w");
510
511    # Fetch all the users
512    global PasswdAttrs;
513    if PasswdAttrs == None:
514       raise "No Users";
515
516    for x in PasswdAttrs:
517       Reason = None
518
519       if x[1].has_key("mailDisableMessage"):
520          Reason = GetAttr(x,"mailDisableMessage")
521       else:
522          continue
523
524       # Must be in the Debian group (yuk, hard coded for now)
525       if GetAttr(x,"gidNumber") != "800":
526          continue;
527
528       try:
529          Line = "%s: %s"%(GetAttr(x,"uid"),Reason);
530          Line = Sanitize(Line) + "\n";
531          F.write(Line);
532       except:
533          pass;
534       
535   # Oops, something unspeakable happened.
536   except:
537    Die(File,F,None);
538    raise;
539   Done(File,F,None);
540
541 # Generate a list of uids that should have boolean affects applied
542 def GenMailBool(l,File,Key):
543   F = None;
544   try:
545    F = open(File + ".tmp","w");
546
547    # Fetch all the users
548    global PasswdAttrs;
549    if PasswdAttrs == None:
550       raise "No Users";
551
552    for x in PasswdAttrs:
553       Reason = None
554       
555       if x[1].has_key(Key) == 0:
556          continue
557
558       # Must be in the Debian group (yuk, hard coded for now)
559       if GetAttr(x,"gidNumber") != "800":
560          continue
561
562       if GetAttr(x,Key) != "TRUE":
563          continue
564
565       try:
566          Line = "%s"%(GetAttr(x,"uid"));
567          Line = Sanitize(Line) + "\n";
568          F.write(Line);
569       except:
570          pass;
571       
572   # Oops, something unspeakable happened.
573   except:
574    Die(File,F,None);
575    raise;
576   Done(File,F,None);
577
578 # Generate a list of hosts for RBL or whitelist purposes.
579 def GenMailList(l,File,Key):
580   F = None;
581   try:
582    F = open(File + ".tmp","w");
583
584    # Fetch all the users
585    global PasswdAttrs;
586    if PasswdAttrs == None:
587       raise "No Users";
588
589    for x in PasswdAttrs:
590       Reason = None
591       
592       if x[1].has_key(Key) == 0:
593          continue
594
595       # Must be in the Debian group (yuk, hard coded for now)
596       if GetAttr(x,"gidNumber") != "800":
597          continue
598
599       try:
600          found = 0
601          Line = None
602          for z in x[1][Key]:
603              if Key == "mailWhitelist":
604                  if re.match('^[-\w.]+(/[\d]+)?$',z) == None:
605                      continue
606              else:
607                  if re.match('^[-\w.]+$',z) == None:
608                      continue
609              if found == 0:
610                  found = 1
611                  Line = GetAttr(x,"uid")
612              else:
613                  Line += " "
614              Line += ": " + z
615              if Key == "mailRHSBL":
616                  Line += "/$sender_address_domain"
617
618          if Line != None:
619              Line = Sanitize(Line) + "\n";
620              F.write(Line);
621       except:
622          pass;
623       
624   # Oops, something unspeakable happened.
625   except:
626    Die(File,F,None);
627    raise;
628   Done(File,F,None);
629
630 # Generate the DNS Zone file
631 def GenDNS(l,File,HomePrefix):
632   F = None;
633   try:
634    F = open(File + ".tmp","w");
635    
636    # Fetch all the users
637    global PasswdAttrs;
638    if PasswdAttrs == None:
639       raise "No Users";
640
641    # Write out the zone file entry for each user
642    for x in PasswdAttrs:
643       if x[1].has_key("dnsZoneEntry") == 0:
644          continue;
645
646       # If the account has no PGP key, do not write it
647       if x[1].has_key("keyFingerPrint") == 0:
648          continue;
649       try:
650          F.write("; %s\n"%(EmailAddress(x)));
651          for z in x[1]["dnsZoneEntry"]:
652             Split = z.lower().split()
653             if Split[1].lower() == 'in':
654                for y in range(0,len(Split)):
655                   if Split[y] == "$":
656                      Split[y] = "\n\t";
657                Line = " ".join(Split) + "\n";
658                F.write(Line);
659                
660                Host = Split[0] + DNSZone;
661                if BSMTPCheck.match(Line) != None:
662                    F.write("; Has BSMTP\n");
663                                
664                # Write some identification information
665                if Split[2].lower() == "a":
666                   Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
667                   for y in x[1]["keyFingerPrint"]:
668                      Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
669                   F.write(Line);
670             else:
671                Line = "; Err %s"%(str(Split));
672                F.write(Line);
673
674          F.write("\n");
675       except:
676          F.write("; Errors\n");
677          pass;
678       
679   # Oops, something unspeakable happened.
680   except:
681    Die(File,F,None);
682    raise;
683   Done(File,F,None);
684
685 # Generate the DNS SSHFP records
686 def GenSSHFP(l,File,HomePrefix):
687   F = None
688   try:
689    F = open(File + ".tmp","w")
690    
691    # Fetch all the hosts
692    global HostAttrs
693    if HostAttrs == None:
694       raise "No Hosts"
695
696    for x in HostAttrs:
697       if x[1].has_key("hostname") == 0 or \
698          x[1].has_key("sshRSAHostKey") == 0:
699          continue
700       Host = GetAttr(x,"hostname");
701       Algorithm = None
702       for I in x[1]["sshRSAHostKey"]:
703          Split = I.split()
704          if Split[0] == 'ssh-rsa':
705             Algorithm = 1
706          if Split[0] == 'ssh-dss':
707             Algorithm = 2
708          if Algorithm == None:
709             continue
710          Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
711          Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
712          Line = Sanitize(Line) + "\n"
713          F.write(Line)
714   # Oops, something unspeakable happened.
715   except:
716    Die(File,F,None)
717    raise;
718   Done(File,F,None)
719
720 # Generate the BSMTP file
721 def GenBSMTP(l,File,HomePrefix):
722   F = None;
723   try:
724    F = open(File + ".tmp","w");
725    
726    # Fetch all the users
727    global PasswdAttrs;
728    if PasswdAttrs == None:
729       raise "No Users";
730
731    # Write out the zone file entry for each user
732    for x in PasswdAttrs:
733       if x[1].has_key("dnsZoneEntry") == 0:
734          continue;
735
736       # If the account has no PGP key, do not write it
737       if x[1].has_key("keyFingerPrint") == 0:
738          continue;
739       try:
740          for z in x[1]["dnsZoneEntry"]:
741             Split = z.lower().split()
742             if Split[1].lower() == 'in':
743                for y in range(0,len(Split)):
744                   if Split[y] == "$":
745                      Split[y] = "\n\t";
746                Line = " ".join(Split) + "\n";
747                
748                Host = Split[0] + DNSZone;
749                if BSMTPCheck.match(Line) != None:
750                    F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
751                                GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
752                                
753       except:
754          F.write("; Errors\n");
755          pass;
756       
757   # Oops, something unspeakable happened.
758   except:
759    Die(File,F,None);
760    raise;
761   Done(File,F,None);
762
763 # cache IP adresses
764 HostToIPCache = {}
765 def HostToIP(Host):
766     global HostToIPCache
767     if not Host in HostToIPCache:
768         IPAdressesT = None
769         try:
770             IPAdressesT = list(set([ (a[0],a[4][0]) for a in socket.getaddrinfo(Host, None)]))
771         except socket.gaierror, (code):
772             if code[0] != -2: raise
773         IPAdresses = []
774         for addr in IPAdressesT:
775             if addr[0] == socket.AF_INET: IPAdresses += [addr[1], "::ffff:"+addr[1]]
776             else: IPAdresses += [addr[1]]
777         HostToIPCache[Host] = IPAdresses
778     return HostToIPCache[Host]
779
780
781 # Generate the ssh known hosts file
782 def GenSSHKnown(l,File,mode=None):
783   F = None;
784   try:
785    OldMask = os.umask(0022);
786    F = open(File + ".tmp","w",0644);
787    os.umask(OldMask);
788
789    global HostAttrs
790    if HostAttrs == None:
791       raise "No Hosts";
792    
793    for x in HostAttrs:
794       if x[1].has_key("hostname") == 0 or \
795          x[1].has_key("sshRSAHostKey") == 0:
796          continue;
797       Host = GetAttr(x,"hostname");
798       HostNames = [ Host ]
799       SHost = Host.find(".")
800       if SHost != None: HostNames += [Host[0:SHost]]
801
802       for I in x[1]["sshRSAHostKey"]:
803          if mode and mode == 'authorized_keys':
804             #Line = 'command="rsync --server --sender -pr . /var/cache/userdir-ldap/hosts/%s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,from="%s" %s' % (Host, ",".join(HNames + HostToIP(Host)), I)
805             Line = 'command="rsync --server --sender -pr . /var/cache/userdir-ldap/hosts/%s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding %s' % (Host,I)
806          else:
807             Line = "%s %s" %(",".join(HostNames + HostToIP(Host)), I);
808          Line = Sanitize(Line) + "\n";
809          F.write(Line);
810   # Oops, something unspeakable happened.
811   except:
812    Die(File,F,None);
813    raise;
814   Done(File,F,None);
815
816 # Generate the debianhosts file (list of all IP addresses)
817 def GenHosts(l,File):
818   F = None;
819   try:
820    OldMask = os.umask(0022);
821    F = open(File + ".tmp","w",0644);
822    os.umask(OldMask);
823
824    # Fetch all the hosts
825    HostNames = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"hostname=*",\
826                 ["hostname"]);
827    
828    if HostNames == None:
829       raise "No Hosts";
830
831    for x in HostNames:
832       if x[1].has_key("hostname") == 0:
833          continue;
834       Host = GetAttr(x,"hostname");
835       try:
836         Addr = socket.gethostbyname(Host);
837         F.write(Addr + "\n");
838       except:
839         pass
840   # Oops, something unspeakable happened.
841   except:
842    Die(File,F,None);
843    raise;
844   Done(File,F,None);
845
846 def GenKeyrings(l,OutDir):
847   for k in Keyrings:
848     shutil.copy(k, OutDir)
849
850 # Connect to the ldap server
851 l = connectLDAP()
852 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
853 Pass = F.readline().strip().split(" ")
854 F.close();
855 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
856
857 # Fetch all the groups
858 GroupIDMap = {};
859 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
860                   ["gid","gidNumber"]);
861
862 # Generate the GroupMap and GroupIDMap
863 for x in Attrs:
864    if x[1].has_key("gidNumber") == 0:
865       continue;
866    GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
867
868 # Fetch all the users
869 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
870                 ["uid","uidNumber","gidNumber","supplementaryGid",\
871                  "gecos","loginShell","userPassword","shadowLastChange",\
872                  "shadowMin","shadowMax","shadowWarning","shadowInactive",
873                  "shadowExpire","emailForward","latitude","longitude",\
874                  "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
875                  "keyFingerPrint","privateSub","mailDisableMessage",\
876                  "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
877                  "mailWhitelist"]);
878 # Fetch all the hosts
879 HostAttrs    = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
880                 ["hostname","sshRSAHostKey"]);
881
882 # Open the control file
883 if len(sys.argv) == 1:
884    F = open(GenerateConf,"r");
885 else:
886    F = open(sys.argv[1],"r")
887
888 # Generate global things
889 GlobalDir = GenerateDir+"/";
890 SSHGlobal, SSHFiles = GenSSHShadow(l,GlobalDir+"ssh-rsa-shadow");
891 GenAllForward(l,GlobalDir+"mail-forward.cdb");
892 GenMarkers(l,GlobalDir+"markers");
893 GenPrivate(l,GlobalDir+"debian-private");
894 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
895 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
896 #GenSSHKnown(l,GlobalDir+"authorized_keys", 'authorized_keys');
897 GenHosts(l,GlobalDir+"debianhosts");
898 GenMailDisable(l,GlobalDir+"mail-disable");
899 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
900 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
901 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
902 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
903 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
904 GenKeyrings(l,GlobalDir);
905
906 # Compatibility.
907 GenForward(l,GlobalDir+"forward-alias");
908
909 while(1):
910    Line = F.readline();
911    if Line == "":
912       break;
913    Line = Line.strip()
914    if Line == "":
915       continue;
916    if Line[0] == '#':
917       continue;
918
919    Split = Line.split(" ")
920    OutDir = GenerateDir + '/' + Split[0] + '/';
921    try: os.mkdir(OutDir);
922    except: pass;
923
924    # Get the group list and convert any named groups to numerics
925    GroupList = {};
926    ExtraList = {};
927    for I in Split[2:]:
928       if I[0] == '[':
929          ExtraList[I] = None;
930          continue;
931       GroupList[I] = None;
932       if GroupIDMap.has_key(I):
933          GroupList[str(GroupIDMap[I])] = None;
934
935    Allowed = GroupList;
936    if Allowed == {}:
937      Allowed = None
938    CurrentHost = Split[0];
939
940    # If we're using a single SSH file, deal with it
941    if SSHGlobal is not None:
942       DoLink(GlobalDir, OutDir, SSHGlobal)
943
944    DoLink(GlobalDir,OutDir,"debianhosts");
945    DoLink(GlobalDir,OutDir,"ssh_known_hosts");
946    DoLink(GlobalDir,OutDir,"disabled-accounts")
947
948    sys.stdout.flush();
949    if ExtraList.has_key("[NOPASSWD]"):
950       userlist = GenPasswd(l,OutDir+"passwd",Split[1], "*");
951    else:
952       userlist = GenPasswd(l,OutDir+"passwd",Split[1], "x");
953    sys.stdout.flush();
954    grouprevmap = GenGroup(l,OutDir+"group");
955
956    # Now we know who we're allowing on the machine, export
957    # the relevant ssh keys
958    if MultipleSSHFiles:
959       OldMask = os.umask(0077);
960       tf = tarfile.open(name=os.path.join(GlobalDir, 'ssh-keys-%s.tar.gz' % CurrentHost), mode='w:gz')
961       os.umask(OldMask);
962       for f in userlist.keys():
963         if f not in SSHFiles:
964             continue
965         # If we're not exporting their primary group, don't export 
966         # the key and warn
967         grname = None
968         if userlist[f] in grouprevmap.keys():
969             grname = grouprevmap[userlist[f]]
970         else:
971             try:
972                 if int(userlist[f]) <= 100:
973                     # In these cases, look it up in the normal way so we
974                     # deal with cases where, for instance, users are in group
975                     # users as their primary group.
976                     grname = grp.getgrgid(userlist[f])[0]
977             except Exception, e:
978                 pass
979
980         if grname is None:
981             print "User %s is supposed to have their key exported to host %s but their primary group (gid: %d) isn't in LDAP" % (f, CurrentHost, userlist[f])
982             continue
983
984         to = tf.gettarinfo(os.path.join(GlobalDir, 'userkeys', f), f)
985         # These will only be used where the username doesn't
986         # exist on the target system for some reason; hence,
987         # in those cases, the safest thing is for the file to
988         # be owned by root but group nobody.  This deals with
989         # the bloody obscure case where the group fails to exist
990         # whilst the user does (in which case we want to avoid
991         # ending up with a file which is owned user:root to avoid
992         # a fairly obvious attack vector)
993         to.uid = 0
994         to.gid = 65534
995         # Using the username / groupname fields avoids any need
996         # to give a shit^W^W^Wcare about the UIDoffset stuff.
997         to.uname = f
998         to.gname = grname
999         to.mode  = 0400
1000         tf.addfile(to, file(os.path.join(GlobalDir, 'userkeys', f)))
1001
1002       tf.close()
1003       os.rename(os.path.join(GlobalDir, 'ssh-keys-%s.tar.gz' % CurrentHost),
1004                 os.path.join(OutDir, 'ssh-keys.tar.gz'))
1005
1006    if ExtraList.has_key("[UNTRUSTED]"):
1007      continue;
1008    if not ExtraList.has_key("[NOPASSWD]"):
1009      GenShadow(l,OutDir+"shadow");
1010
1011    # Link in global things   
1012    DoLink(GlobalDir,OutDir,"markers");
1013    DoLink(GlobalDir,OutDir,"mail-forward.cdb");
1014    DoLink(GlobalDir,OutDir,"mail-disable");
1015    DoLink(GlobalDir,OutDir,"mail-greylist");
1016    DoLink(GlobalDir,OutDir,"mail-callout");
1017    DoLink(GlobalDir,OutDir,"mail-rbl");
1018    DoLink(GlobalDir,OutDir,"mail-rhsbl");
1019    DoLink(GlobalDir,OutDir,"mail-whitelist");
1020
1021    # Compatibility.
1022    DoLink(GlobalDir,OutDir,"forward-alias");
1023
1024    if ExtraList.has_key("[DNS]"):
1025       GenDNS(l,OutDir+"dns-zone",Split[1]);
1026       GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
1027       
1028    if ExtraList.has_key("[BSMTP]"):
1029       GenBSMTP(l,OutDir+"bsmtp",Split[1])
1030
1031    if ExtraList.has_key("[PRIVATE]"):
1032       DoLink(GlobalDir,OutDir,"debian-private")
1033
1034    if ExtraList.has_key("[KEYRING]"):
1035       for k in Keyrings:
1036         DoLink(GlobalDir,OutDir,os.path.basename(k))
1037    else:
1038      for k in Keyrings:
1039        try: posix.remove(OutDir+os.path.basename(k));
1040        except: pass;