Patch by Thomas Viehmann: Also add IPv6 to debianhosts
[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 # Generate the DNS Zone file
739 def GenDNS(l,File,HomePrefix):
740   F = None;
741   try:
742    F = open(File + ".tmp","w");
743
744    # Fetch all the users
745    global PasswdAttrs;
746    if PasswdAttrs == None:
747       raise "No Users";
748
749    # Write out the zone file entry for each user
750    for x in PasswdAttrs:
751       if x[1].has_key("dnsZoneEntry") == 0:
752          continue;
753
754       # If the account has no PGP key, do not write it
755       if x[1].has_key("keyFingerPrint") == 0:
756          continue;
757       try:
758          F.write("; %s\n"%(EmailAddress(x)));
759          for z in x[1]["dnsZoneEntry"]:
760             Split = z.lower().split()
761             if Split[1].lower() == 'in':
762                for y in range(0,len(Split)):
763                   if Split[y] == "$":
764                      Split[y] = "\n\t";
765                Line = " ".join(Split) + "\n";
766                F.write(Line);
767
768                Host = Split[0] + DNSZone;
769                if BSMTPCheck.match(Line) != None:
770                    F.write("; Has BSMTP\n");
771
772                # Write some identification information
773                if Split[2].lower() == "a":
774                   Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
775                   for y in x[1]["keyFingerPrint"]:
776                      Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
777                   F.write(Line);
778             else:
779                Line = "; Err %s"%(str(Split));
780                F.write(Line);
781
782          F.write("\n");
783       except:
784          F.write("; Errors\n");
785          pass;
786
787   # Oops, something unspeakable happened.
788   except:
789    Die(File,F,None);
790    raise;
791   Done(File,F,None);
792
793 # Generate the DNS SSHFP records
794 def GenSSHFP(l,File,HomePrefix):
795   F = None
796   try:
797    F = open(File + ".tmp","w")
798
799    # Fetch all the hosts
800    global HostAttrs
801    if HostAttrs == None:
802       raise "No Hosts"
803
804    for x in HostAttrs:
805       if x[1].has_key("hostname") == 0 or \
806          x[1].has_key("sshRSAHostKey") == 0:
807          continue
808       Host = GetAttr(x,"hostname");
809       Algorithm = None
810       for I in x[1]["sshRSAHostKey"]:
811          Split = I.split()
812          if Split[0] == 'ssh-rsa':
813             Algorithm = 1
814          if Split[0] == 'ssh-dss':
815             Algorithm = 2
816          if Algorithm == None:
817             continue
818          Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
819          Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
820          Line = Sanitize(Line) + "\n"
821          F.write(Line)
822   # Oops, something unspeakable happened.
823   except:
824    Die(File,F,None)
825    raise;
826   Done(File,F,None)
827
828 # Generate the BSMTP file
829 def GenBSMTP(l,File,HomePrefix):
830   F = None;
831   try:
832    F = open(File + ".tmp","w");
833
834    # Fetch all the users
835    global PasswdAttrs;
836    if PasswdAttrs == None:
837       raise "No Users";
838
839    # Write out the zone file entry for each user
840    for x in PasswdAttrs:
841       if x[1].has_key("dnsZoneEntry") == 0:
842          continue;
843
844       # If the account has no PGP key, do not write it
845       if x[1].has_key("keyFingerPrint") == 0:
846          continue;
847       try:
848          for z in x[1]["dnsZoneEntry"]:
849             Split = z.lower().split()
850             if Split[1].lower() == 'in':
851                for y in range(0,len(Split)):
852                   if Split[y] == "$":
853                      Split[y] = "\n\t";
854                Line = " ".join(Split) + "\n";
855
856                Host = Split[0] + DNSZone;
857                if BSMTPCheck.match(Line) != None:
858                    F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
859                                GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
860
861       except:
862          F.write("; Errors\n");
863          pass;
864
865   # Oops, something unspeakable happened.
866   except:
867    Die(File,F,None);
868    raise;
869   Done(File,F,None);
870
871 # cache IP adresses
872 HostToIPCache = {}
873 def HostToIP(Host):
874     global HostToIPCache
875     if not Host in HostToIPCache:
876         IPAdressesT = None
877         try:
878             IPAdressesT = list(set([ (a[0],a[4][0]) for a in socket.getaddrinfo(Host, None)]))
879         except socket.gaierror, (code):
880             if code[0] != -2: raise
881         IPAdresses = []
882         for addr in IPAdressesT:
883             if addr[0] == socket.AF_INET: IPAdresses += [addr[1], "::ffff:"+addr[1]]
884             else: IPAdresses += [addr[1]]
885         HostToIPCache[Host] = IPAdresses
886     return HostToIPCache[Host]
887
888
889 # Generate the ssh known hosts file
890 def GenSSHKnown(l,File,mode=None):
891   F = None;
892   try:
893    OldMask = os.umask(0022);
894    F = open(File + ".tmp","w",0644);
895    os.umask(OldMask);
896
897    global HostAttrs
898    if HostAttrs == None:
899       raise "No Hosts";
900
901    for x in HostAttrs:
902       if x[1].has_key("hostname") == 0 or \
903          x[1].has_key("sshRSAHostKey") == 0:
904          continue;
905       Host = GetAttr(x,"hostname");
906       HostNames = [ Host ]
907       if Host.endswith(HostDomain):
908          HostNames.append(Host[:-(len(HostDomain)+1)])
909
910       # in the purpose field [[host|some other text]] (where some other text is optional)
911       # makes a hyperlink on the web thing. we now also add these hosts to the ssh known_hosts
912       # file.  But so that we don't have to add everything we link we can add an asterisk
913       # and say [[*... to ignore it.  In order to be able to add stuff to ssh without
914       # http linking it we also support [[-hostname]] entries.
915       for i in x[1].get("purpose",[]):
916          m = PurposeHostField.match(i)
917          if m:
918             m = m.group(1)
919             # we ignore [[*..]] entries
920             if m.startswith('*'):
921                continue;
922             if m.startswith('-'):
923                m = m[1:]
924             if m:
925                HostNames.append(m)
926                if m.endswith(HostDomain):
927                   HostNames.append(m[:-(len(HostDomain)+1)])
928
929       for I in x[1]["sshRSAHostKey"]:
930          if mode and mode == 'authorized_keys':
931             #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)
932             Line = 'command="rsync --server --sender -pr . /var/cache/userdir-ldap/hosts/%s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding %s' % (Host,I)
933          else:
934             Line = "%s %s" %(",".join(HostNames + HostToIP(Host)), I);
935          Line = Sanitize(Line) + "\n";
936          F.write(Line);
937   # Oops, something unspeakable happened.
938   except:
939    Die(File,F,None);
940    raise;
941   Done(File,F,None);
942
943 # Generate the debianhosts file (list of all IP addresses)
944 def GenHosts(l,File):
945   F = None
946   try:
947     OldMask = os.umask(0022)
948     F = open(File + ".tmp","w",0644)
949     os.umask(OldMask)
950
951     # Fetch all the hosts
952     hostnames = l.search_s(HostBaseDn, ldap.SCOPE_ONELEVEL, "hostname=*",
953                            ["hostname"])
954
955     if hostnames == None:
956        raise "No Hosts"
957
958     seen = set()
959     for x in hostnames:
960       host = GetAttr(x,"hostname", None)
961       if host:
962         addrs = []
963         try:
964           addrs += socket.getaddrinfo(host, None, socket.AF_INET)
965         except socket.error:
966           pass
967         try:
968           addrs += socket.getaddrinfo(host, None, socket.AF_INET6)
969         except socket.error:
970           pass
971
972         for addrinfo in addrs:
973           if addrinfo[0] in (socket.AF_INET, socket.AF_INET6):
974             addr = addrinfo[4][0]
975             if addr not in seen:
976               print >> F, addrinfo[4][0]
977               seen.add(addr)
978   # Oops, something unspeakable happened.
979   except:
980     Die(File,F,None)
981     raise
982   Done(File,F,None)
983
984 def GenKeyrings(l,OutDir):
985   for k in Keyrings:
986     shutil.copy(k, OutDir)
987
988
989 # Connect to the ldap server
990 l = connectLDAP()
991 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
992 Pass = F.readline().strip().split(" ")
993 F.close();
994 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
995
996 # Fetch all the groups
997 GroupIDMap = {};
998 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
999                   ["gid","gidNumber","subGroup"]);
1000
1001 # Generate the SubGroupMap and GroupIDMap
1002 for x in Attrs:
1003    if x[1].has_key("gidNumber") == 0:
1004       continue;
1005    GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
1006    if x[1].has_key("subGroup") != 0:
1007       SubGroupMap.setdefault(x[1]["gid"][0], []).extend(x[1]["subGroup"]);
1008
1009 # Fetch all the users
1010 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
1011                 ["uid","uidNumber","gidNumber","supplementaryGid",\
1012                  "gecos","loginShell","userPassword","shadowLastChange",\
1013                  "shadowMin","shadowMax","shadowWarning","shadowInactive",
1014                  "shadowExpire","emailForward","latitude","longitude",\
1015                  "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
1016                  "keyFingerPrint","privateSub","mailDisableMessage",\
1017                  "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
1018                  "mailWhitelist", "sudoPassword"]);
1019 # Fetch all the hosts
1020 HostAttrs    = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
1021                 ["hostname","sshRSAHostKey","purpose"]);
1022
1023 # Open the control file
1024 if len(sys.argv) == 1:
1025    F = open(GenerateConf,"r");
1026 else:
1027    F = open(sys.argv[1],"r")
1028
1029 # Generate global things
1030 GlobalDir = GenerateDir+"/";
1031 SSHFiles = GenSSHShadow(l);
1032 GenAllForward(l,GlobalDir+"mail-forward.cdb");
1033 GenMarkers(l,GlobalDir+"markers");
1034 GenPrivate(l,GlobalDir+"debian-private");
1035 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
1036 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
1037 #GenSSHKnown(l,GlobalDir+"authorized_keys", 'authorized_keys');
1038 GenHosts(l,GlobalDir+"debianhosts");
1039 GenMailDisable(l,GlobalDir+"mail-disable");
1040 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
1041 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
1042 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
1043 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
1044 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
1045 GenKeyrings(l,GlobalDir);
1046
1047 # Compatibility.
1048 GenForward(l,GlobalDir+"forward-alias");
1049
1050 while(1):
1051    Line = F.readline();
1052    if Line == "":
1053       break;
1054    Line = Line.strip()
1055    if Line == "":
1056       continue;
1057    if Line[0] == '#':
1058       continue;
1059
1060    Split = Line.split(" ")
1061    OutDir = GenerateDir + '/' + Split[0] + '/';
1062    try: os.mkdir(OutDir);
1063    except: pass;
1064
1065    # Get the group list and convert any named groups to numerics
1066    GroupList = {};
1067    ExtraList = {};
1068    for I in Split[2:]:
1069       if I[0] == '[':
1070          ExtraList[I] = None;
1071          continue;
1072       GroupList[I] = None;
1073       if GroupIDMap.has_key(I):
1074          GroupList[str(GroupIDMap[I])] = None;
1075
1076    Allowed = GroupList;
1077    if Allowed == {}:
1078      Allowed = None
1079    CurrentHost = Split[0];
1080
1081    DoLink(GlobalDir,OutDir,"debianhosts");
1082    DoLink(GlobalDir,OutDir,"ssh_known_hosts");
1083    DoLink(GlobalDir,OutDir,"disabled-accounts")
1084
1085    sys.stdout.flush();
1086    if ExtraList.has_key("[NOPASSWD]"):
1087       userlist = GenPasswd(l,OutDir+"passwd",Split[1], "*");
1088    else:
1089       userlist = GenPasswd(l,OutDir+"passwd",Split[1], "x");
1090    sys.stdout.flush();
1091    grouprevmap = GenGroup(l,OutDir+"group");
1092    GenShadowSudo(l, OutDir+"sudo-passwd", ExtraList.has_key("[UNTRUSTED]") or ExtraList.has_key("[NOPASSWD]"))
1093
1094    # Now we know who we're allowing on the machine, export
1095    # the relevant ssh keys
1096    GenSSHtarballs(userlist, SSHFiles, grouprevmap, os.path.join(OutDir, 'ssh-keys.tar.gz'))
1097
1098    if ExtraList.has_key("[UNTRUSTED]"):
1099      print "[UNTRUSTED] tag is obsolete and may be removed in the future."
1100      continue;
1101    if not ExtraList.has_key("[NOPASSWD]"):
1102      GenShadow(l,OutDir+"shadow");
1103
1104    # Link in global things
1105    if not ExtraList.has_key("[NOMARKERS]"):
1106      DoLink(GlobalDir,OutDir,"markers");
1107    DoLink(GlobalDir,OutDir,"mail-forward.cdb");
1108    DoLink(GlobalDir,OutDir,"mail-disable");
1109    DoLink(GlobalDir,OutDir,"mail-greylist");
1110    DoLink(GlobalDir,OutDir,"mail-callout");
1111    DoLink(GlobalDir,OutDir,"mail-rbl");
1112    DoLink(GlobalDir,OutDir,"mail-rhsbl");
1113    DoLink(GlobalDir,OutDir,"mail-whitelist");
1114
1115    # Compatibility.
1116    DoLink(GlobalDir,OutDir,"forward-alias");
1117
1118    if ExtraList.has_key("[DNS]"):
1119       GenDNS(l,OutDir+"dns-zone",Split[1]);
1120       GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
1121
1122    if ExtraList.has_key("[BSMTP]"):
1123       GenBSMTP(l,OutDir+"bsmtp",Split[1])
1124
1125    if ExtraList.has_key("[PRIVATE]"):
1126       DoLink(GlobalDir,OutDir,"debian-private")
1127
1128    if ExtraList.has_key("[KEYRING]"):
1129       for k in Keyrings:
1130         DoLink(GlobalDir,OutDir,os.path.basename(k))
1131    else:
1132      for k in Keyrings:
1133        try: posix.remove(OutDir+os.path.basename(k));
1134        except: pass;
1135
1136 # vim:set et:
1137 # vim:set ts=3:
1138 # vim:set shiftwidth=3: