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