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