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