Merge from -common branch
[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 Mark Hymers <mhy@debian.org>
11 #
12 #   This program is free software; you can redistribute it and/or modify
13 #   it under the terms of the GNU General Public License as published by
14 #   the Free Software Foundation; either version 2 of the License, or
15 #   (at your option) any later version.
16 #
17 #   This program is distributed in the hope that it will be useful,
18 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
19 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 #   GNU General Public License for more details.
21 #
22 #   You should have received a copy of the GNU General Public License
23 #   along with this program; if not, write to the Free Software
24 #   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25
26 import string, re, time, ldap, getopt, sys, os, pwd, posix, socket, base64, sha, shutil, errno, tarfile, grp
27 from userdir_ldap import *;
28
29 global Allowed;
30 global CurrentHost;
31
32 PasswdAttrs = None;
33 GroupIDMap = {};
34 Allowed = None;
35 CurrentHost = "";
36
37 EmailCheck = re.compile("^([^ <>@]+@[^ ,<>@]+)?$");
38 BSMTPCheck = re.compile(".*mx 0 (gluck)\.debian\.org\..*",re.DOTALL);
39 DNSZone = ".debian.net"
40 Keyrings = [ "/org/keyring.debian.org/keyrings/debian-keyring.gpg",
41              "/org/keyring.debian.org/keyrings/debian-keyring.pgp" ]
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")] = 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 the account is locked, disable incoming mail
520       if (GetAttr(x,"userPassword").find("*LK*") != -1):
521          if GetAttr(x,"uid") == "luther":
522             continue
523          else:
524             Reason = "user account locked"
525       else:
526          if x[1].has_key("mailDisableMessage"):
527             Reason = GetAttr(x,"mailDisableMessage")
528          else:
529             continue
530
531       # Must be in the Debian group (yuk, hard coded for now)
532       if GetAttr(x,"gidNumber") != "800":
533          continue;
534
535       try:
536          Line = "%s: %s"%(GetAttr(x,"uid"),Reason);
537          Line = Sanitize(Line) + "\n";
538          F.write(Line);
539       except:
540          pass;
541       
542   # Oops, something unspeakable happened.
543   except:
544    Die(File,F,None);
545    raise;
546   Done(File,F,None);
547
548 # Generate a list of uids that should have boolean affects applied
549 def GenMailBool(l,File,Key):
550   F = None;
551   try:
552    F = open(File + ".tmp","w");
553
554    # Fetch all the users
555    global PasswdAttrs;
556    if PasswdAttrs == None:
557       raise "No Users";
558
559    for x in PasswdAttrs:
560       Reason = None
561       
562       if x[1].has_key(Key) == 0:
563          continue
564
565       # Must be in the Debian group (yuk, hard coded for now)
566       if GetAttr(x,"gidNumber") != "800":
567          continue
568
569       if GetAttr(x,Key) != "TRUE":
570          continue
571
572       try:
573          Line = "%s"%(GetAttr(x,"uid"));
574          Line = Sanitize(Line) + "\n";
575          F.write(Line);
576       except:
577          pass;
578       
579   # Oops, something unspeakable happened.
580   except:
581    Die(File,F,None);
582    raise;
583   Done(File,F,None);
584
585 # Generate a list of hosts for RBL or whitelist purposes.
586 def GenMailList(l,File,Key):
587   F = None;
588   try:
589    F = open(File + ".tmp","w");
590
591    # Fetch all the users
592    global PasswdAttrs;
593    if PasswdAttrs == None:
594       raise "No Users";
595
596    for x in PasswdAttrs:
597       Reason = None
598       
599       if x[1].has_key(Key) == 0:
600          continue
601
602       # Must be in the Debian group (yuk, hard coded for now)
603       if GetAttr(x,"gidNumber") != "800":
604          continue
605
606       try:
607          found = 0
608          Line = None
609          for z in x[1][Key]:
610              if Key == "mailWhitelist":
611                  if re.match('^[-\w.]+(/[\d]+)?$',z) == None:
612                      continue
613              else:
614                  if re.match('^[-\w.]+$',z) == None:
615                      continue
616              if found == 0:
617                  found = 1
618                  Line = GetAttr(x,"uid")
619              else:
620                  Line += " "
621              Line += ": " + z
622              if Key == "mailRHSBL":
623                  Line += "/$sender_address_domain"
624
625          if Line != None:
626              Line = Sanitize(Line) + "\n";
627              F.write(Line);
628       except:
629          pass;
630       
631   # Oops, something unspeakable happened.
632   except:
633    Die(File,F,None);
634    raise;
635   Done(File,F,None);
636
637 # Generate the DNS Zone file
638 def GenDNS(l,File,HomePrefix):
639   F = None;
640   try:
641    F = open(File + ".tmp","w");
642    
643    # Fetch all the users
644    global PasswdAttrs;
645    if PasswdAttrs == None:
646       raise "No Users";
647
648    # Write out the zone file entry for each user
649    for x in PasswdAttrs:
650       if x[1].has_key("dnsZoneEntry") == 0:
651          continue;
652
653       # If the account has no PGP key, do not write it
654       if x[1].has_key("keyFingerPrint") == 0:
655          continue;
656       try:
657          F.write("; %s\n"%(EmailAddress(x)));
658          for z in x[1]["dnsZoneEntry"]:
659             Split = z.lower().split()
660             if Split[1].lower() == 'in':
661                for y in range(0,len(Split)):
662                   if Split[y] == "$":
663                      Split[y] = "\n\t";
664                Line = " ".join(Split) + "\n";
665                F.write(Line);
666                
667                Host = Split[0] + DNSZone;
668                if BSMTPCheck.match(Line) != None:
669                    F.write("; Has BSMTP\n");
670                                
671                # Write some identification information
672                if Split[2].lower() == "a":
673                   Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
674                   for y in x[1]["keyFingerPrint"]:
675                      Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
676                   F.write(Line);
677             else:
678                Line = "; Err %s"%(str(Split));
679                F.write(Line);
680
681          F.write("\n");
682       except:
683          F.write("; Errors\n");
684          pass;
685       
686   # Oops, something unspeakable happened.
687   except:
688    Die(File,F,None);
689    raise;
690   Done(File,F,None);
691
692 # Generate the DNS SSHFP records
693 def GenSSHFP(l,File,HomePrefix):
694   F = None
695   try:
696    F = open(File + ".tmp","w")
697    
698    # Fetch all the hosts
699    global HostAttrs
700    if HostAttrs == None:
701       raise "No Hosts"
702
703    for x in HostAttrs:
704       if x[1].has_key("hostname") == 0 or \
705          x[1].has_key("sshRSAHostKey") == 0:
706          continue
707       Host = GetAttr(x,"hostname");
708       Algorithm = None
709       for I in x[1]["sshRSAHostKey"]:
710          Split = I.split()
711          if Split[0] == 'ssh-rsa':
712             Algorithm = 1
713          if Split[0] == 'ssh-dss':
714             Algorithm = 2
715          if Algorithm == None:
716             continue
717          Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
718          Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
719          Line = Sanitize(Line) + "\n"
720          F.write(Line)
721   # Oops, something unspeakable happened.
722   except:
723    Die(File,F,None)
724    raise;
725   Done(File,F,None)
726
727 # Generate the BSMTP file
728 def GenBSMTP(l,File,HomePrefix):
729   F = None;
730   try:
731    F = open(File + ".tmp","w");
732    
733    # Fetch all the users
734    global PasswdAttrs;
735    if PasswdAttrs == None:
736       raise "No Users";
737
738    # Write out the zone file entry for each user
739    for x in PasswdAttrs:
740       if x[1].has_key("dnsZoneEntry") == 0:
741          continue;
742
743       # If the account has no PGP key, do not write it
744       if x[1].has_key("keyFingerPrint") == 0:
745          continue;
746       try:
747          for z in x[1]["dnsZoneEntry"]:
748             Split = z.lower().split()
749             if Split[1].lower() == 'in':
750                for y in range(0,len(Split)):
751                   if Split[y] == "$":
752                      Split[y] = "\n\t";
753                Line = " ".join(Split) + "\n";
754                
755                Host = Split[0] + DNSZone;
756                if BSMTPCheck.match(Line) != None:
757                    F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
758                                GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
759                                
760       except:
761          F.write("; Errors\n");
762          pass;
763       
764   # Oops, something unspeakable happened.
765   except:
766    Die(File,F,None);
767    raise;
768   Done(File,F,None);
769
770 # Generate the ssh known hosts file
771 def GenSSHKnown(l,File):
772   F = None;
773   try:
774    OldMask = os.umask(0022);
775    F = open(File + ".tmp","w",0644);
776    os.umask(OldMask);
777
778    global HostAttrs
779    if HostAttrs == None:
780       raise "No Hosts";
781    
782    for x in HostAttrs:
783       if x[1].has_key("hostname") == 0 or \
784          x[1].has_key("sshRSAHostKey") == 0:
785          continue;
786       Host = GetAttr(x,"hostname");
787       HostNames = [ Host ]
788       SHost = Host.find(".")
789       if SHost != None: HostNames += [Host[0:SHost]]
790
791       IPAdressesT = None
792       IPAdresses = []
793       # get IP adresses back as "proto adress" to distinguish between v4 and v6
794       try:
795          IPAdressesT = set([ (a[0],a[4][0]) for a in socket.getaddrinfo(Host, None)])
796       except:
797          if code[0] != -2: raise
798       for addr in IPAdressesT:
799          if addr[0] == socket.AF_INET: IPAdresses += [addr[1], "::ffff:"+addr[1]]
800          else: IPAdresses += [addr[1]]
801
802       for I in x[1]["sshRSAHostKey"]:
803          Line = "%s %s" %(",".join(HostNames + IPAdresses), I);
804          Line = Sanitize(Line) + "\n";
805          F.write(Line);
806   # Oops, something unspeakable happened.
807   except:
808    Die(File,F,None);
809    raise;
810   Done(File,F,None);
811
812 # Generate the debianhosts file (list of all IP addresses)
813 def GenHosts(l,File):
814   F = None;
815   try:
816    OldMask = os.umask(0022);
817    F = open(File + ".tmp","w",0644);
818    os.umask(OldMask);
819
820    # Fetch all the hosts
821    HostNames = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"hostname=*",\
822                 ["hostname"]);
823    
824    if HostNames == None:
825       raise "No Hosts";
826
827    for x in HostNames:
828       if x[1].has_key("hostname") == 0:
829          continue;
830       Host = GetAttr(x,"hostname");
831       try:
832         Addr = socket.gethostbyname(Host);
833         F.write(Addr + "\n");
834       except:
835         pass
836   # Oops, something unspeakable happened.
837   except:
838    Die(File,F,None);
839    raise;
840   Done(File,F,None);
841
842 def GenKeyrings(l,OutDir):
843   for k in Keyrings:
844     shutil.copy(k, OutDir)
845
846 # Connect to the ldap server
847 l = ldap.open(LDAPServer);
848 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
849 Pass = F.readline().strip().split(" ")
850 F.close();
851 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
852
853 # Fetch all the groups
854 GroupIDMap = {};
855 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
856                   ["gid","gidNumber"]);
857
858 # Generate the GroupMap and GroupIDMap
859 for x in Attrs:
860    if x[1].has_key("gidNumber") == 0:
861       continue;
862    GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
863
864 # Fetch all the users
865 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
866                 ["uid","uidNumber","gidNumber","supplementaryGid",\
867                  "gecos","loginShell","userPassword","shadowLastChange",\
868                  "shadowMin","shadowMax","shadowWarning","shadowinactive",
869                  "shadowexpire","emailForward","latitude","longitude",\
870                  "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
871                  "keyFingerPrint","privateSub","mailDisableMessage",\
872                  "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
873                  "mailWhitelist"]);
874 # Fetch all the hosts
875 HostAttrs    = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
876                 ["hostname","sshRSAHostKey"]);
877
878 # Open the control file
879 if len(sys.argv) == 1:
880    F = open(GenerateConf,"r");
881 else:
882    F = open(sys.argv[1],"r")
883
884 # Generate global things
885 GlobalDir = GenerateDir+"/";
886 SSHGlobal, SSHFiles = GenSSHShadow(l,GlobalDir+"ssh-rsa-shadow");
887 GenAllForward(l,GlobalDir+"mail-forward.cdb");
888 GenMarkers(l,GlobalDir+"markers");
889 GenPrivate(l,GlobalDir+"debian-private");
890 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
891 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
892 GenHosts(l,GlobalDir+"debianhosts");
893 GenMailDisable(l,GlobalDir+"mail-disable");
894 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
895 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
896 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
897 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
898 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
899 GenKeyrings(l,GlobalDir);
900
901 # Compatibility.
902 GenForward(l,GlobalDir+"forward-alias");
903
904 while(1):
905    Line = F.readline();
906    if Line == "":
907       break;
908    Line = Line.strip()
909    if Line == "":
910       continue;
911    if Line[0] == '#':
912       continue;
913
914    Split = Line.split(" ")
915    OutDir = GenerateDir + '/' + Split[0] + '/';
916    try: os.mkdir(OutDir);
917    except: pass;
918
919    # Get the group list and convert any named groups to numerics
920    GroupList = {};
921    ExtraList = {};
922    for I in Split[2:]:
923       if I[0] == '[':
924          ExtraList[I] = None;
925          continue;
926       GroupList[I] = None;
927       if GroupIDMap.has_key(I):
928          GroupList[str(GroupIDMap[I])] = None;
929
930    Allowed = GroupList;
931    if Allowed == {}:
932      Allowed = None
933    CurrentHost = Split[0];
934
935    # If we're using a single SSH file, deal with it
936    if SSHGlobal is not None:
937       DoLink(GlobalDir, OutDir, SSHGlobal)
938
939    DoLink(GlobalDir,OutDir,"debianhosts");
940    DoLink(GlobalDir,OutDir,"ssh_known_hosts");
941    DoLink(GlobalDir,OutDir,"disabled-accounts")
942
943    sys.stdout.flush();
944    if ExtraList.has_key("[NOPASSWD]"):
945       userlist = GenPasswd(l,OutDir+"passwd",Split[1], "*");
946    else:
947       userlist = GenPasswd(l,OutDir+"passwd",Split[1], "x");
948    sys.stdout.flush();
949    grouprevmap = GenGroup(l,OutDir+"group");
950    if ExtraList.has_key("[UNTRUSTED]"):
951         continue;
952    if not ExtraList.has_key("[NOPASSWD]"):
953      GenShadow(l,OutDir+"shadow");
954
955    # Now we know who we're allowing on the machine, export
956    # the relevant ssh keys
957    if MultipleSSHFiles:
958       tf = tarfile.open(name=os.path.join(GlobalDir, 'ssh-keys-%s.tar.gz' % CurrentHost), mode='w:gz')
959       for f in userlist.keys():
960         if f not in SSHFiles:
961             continue
962         # If we're not exporting their primary group, don't export 
963         # the key and warn
964         grname = None
965         if userlist[f] in grouprevmap.keys():
966             grname = grouprevmap[userlist[f]]
967         else:
968             try:
969                 if int(userlist[f]) <= 100:
970                     # In these cases, look it up in the normal way so we
971                     # deal with cases where, for instance, users are in group
972                     # users as their primary group.
973                     grname = grp.getgrgid(int(userlist[f]))[0]
974             except Exception, e:
975                 pass
976
977         if grname is None:
978             print "User %s is supposed to have their key exported to host %s but their primary group (gid: %s) isn't in LDAP" % (f, CurrentHost, userlist[f])
979             continue
980
981         to = tf.gettarinfo(os.path.join(GlobalDir, 'userkeys', f), f)
982         # These will only be used where the username doesn't
983         # exist on the target system for some reason; hence,
984         # in those cases, the safest thing is for the file to
985         # be owned by root but group nobody.  This deals with
986         # the bloody obscure case where the group fails to exist
987         # whilst the user does (in which case we want to avoid
988         # ending up with a file which is owned user:root to avoid
989         # a fairly obvious attack vector)
990         to.uid = 0
991         to.gid = 65534
992         # Using the username / groupname fields avoids any need
993         # to give a shit^W^W^Wcare about the UIDoffset stuff.
994         to.uname = f
995         to.gname = grname
996         to.mode  = 0600
997         tf.addfile(to, file(os.path.join(GlobalDir, 'userkeys', f)))
998
999       tf.close()
1000       os.rename(os.path.join(GlobalDir, 'ssh-keys-%s.tar.gz' % CurrentHost),
1001                 os.path.join(OutDir, 'ssh-keys.tar.gz'))
1002
1003    # Link in global things   
1004    DoLink(GlobalDir,OutDir,"markers");
1005    DoLink(GlobalDir,OutDir,"mail-forward.cdb");
1006    DoLink(GlobalDir,OutDir,"mail-disable");
1007    DoLink(GlobalDir,OutDir,"mail-greylist");
1008    DoLink(GlobalDir,OutDir,"mail-callout");
1009    DoLink(GlobalDir,OutDir,"mail-rbl");
1010    DoLink(GlobalDir,OutDir,"mail-rhsbl");
1011    DoLink(GlobalDir,OutDir,"mail-whitelist");
1012
1013    # Compatibility.
1014    DoLink(GlobalDir,OutDir,"forward-alias");
1015
1016    if ExtraList.has_key("[DNS]"):
1017       GenDNS(l,OutDir+"dns-zone",Split[1]);
1018       GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
1019       
1020    if ExtraList.has_key("[BSMTP]"):
1021       GenBSMTP(l,OutDir+"bsmtp",Split[1])
1022
1023    if ExtraList.has_key("[PRIVATE]"):
1024       DoLink(GlobalDir,OutDir,"debian-private")
1025
1026    if ExtraList.has_key("[KEYRING]"):
1027       for k in Keyrings:
1028         DoLink(GlobalDir,OutDir,os.path.basename(k))
1029    else:
1030      for k in Keyrings:
1031        try: posix.remove(OutDir+os.path.basename(k));
1032        except: pass;