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