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