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