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