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