generate debianhosts file for exim and possibly other uses
[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) 2001-2005  Ryan Murray <rmurray@debian.org>
7 #   Copyright (c) 2003-2004  James Troup <troup@debian.org>
8 #   Copyright (c) 2004-2005  Joey Schulze <joey@infodrom.org>
9 #
10 #   This program is free software; you can redistribute it and/or modify
11 #   it under the terms of the GNU General Public License as published by
12 #   the Free Software Foundation; either version 2 of the License, or
13 #   (at your option) any later version.
14 #
15 #   This program is distributed in the hope that it will be useful,
16 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
17 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 #   GNU General Public License for more details.
19 #
20 #   You should have received a copy of the GNU General Public License
21 #   along with this program; if not, write to the Free Software
22 #   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23
24 import string, re, time, ldap, getopt, sys, os, pwd, posix, socket;
25 from userdir_ldap import *;
26
27 global Allowed;
28 global CurrentHost;
29
30 PasswdAttrs = None;
31 GroupIDMap = {};
32 Allowed = None;
33 CurrentHost = "";
34
35 EmailCheck = re.compile("^([^ <>@]+@[^ ,<>@]+)?$");
36 BSMTPCheck = re.compile(".*mx 0 (klecker|gluck)\.debian\.org\..*",re.DOTALL);
37 DNSZone = ".debian.net"
38
39 def Sanitize(Str):
40   return string.translate(Str,string.maketrans("\n\r\t","$$$"));
41
42 def DoLink(From,To,File):
43    try: posix.remove(To+File);
44    except: pass;
45    posix.link(From+File,To+File);
46
47 # See if this user is in the group list
48 def IsInGroup(DnRecord):
49   if Allowed == None:
50      return 1;
51
52   # See if the primary group is in the list
53   if Allowed.has_key(GetAttr(DnRecord,"gidNumber")) != 0:
54      return 1;
55
56   # Check the host based ACL
57   if DnRecord[1].has_key("allowedHost") != 0:
58      for I in DnRecord[1]["allowedHost"]:
59         if CurrentHost == I:
60            return 1;
61
62   # See if there are supplementary groups
63   if DnRecord[1].has_key("supplementaryGid") == 0:
64      return 0;
65
66   # Check the supplementary groups
67   for I in DnRecord[1]["supplementaryGid"]:
68      if Allowed.has_key(I):
69         return 1;
70   return 0;
71
72 def Die(File,F,Fdb):
73    if F != None:
74       F.close();
75    if Fdb != None:
76       Fdb.close();
77    try: os.remove(File + ".tmp");
78    except: pass;
79    try: os.remove(File + ".tdb.tmp");
80    except: pass;
81
82 def Done(File,F,Fdb):
83   if F != None:
84     F.close();
85     os.rename(File + ".tmp",File);
86   if Fdb != None:
87     Fdb.close();
88     os.rename(File + ".tdb.tmp",File+".tdb");
89   
90 # Generate the password list
91 def GenPasswd(l,File,HomePrefix):
92   F = None;
93   try:
94    F = open(File + ".tdb.tmp","w");
95
96    # Fetch all the users
97    global PasswdAttrs;
98    if PasswdAttrs == None:
99       raise "No Users";
100
101    I = 0;
102    for x in PasswdAttrs:
103       if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
104          continue;
105
106       # Do not let people try to buffer overflow some busted passwd parser.
107       if len(GetAttr(x,"gecos")) > 100 or len(GetAttr(x,"loginShell")) > 50:
108          continue;
109
110       Line = "%s:x:%s:%s:%s:%s%s:%s" % (GetAttr(x,"uid"),\
111               GetAttr(x,"uidNumber"),GetAttr(x,"gidNumber"),\
112               GetAttr(x,"gecos"),HomePrefix,GetAttr(x,"uid"),\
113               GetAttr(x,"loginShell"));
114
115       Line = Sanitize(Line) + "\n";
116       F.write("0%u %s" % (I,Line));
117       F.write(".%s %s" % (GetAttr(x,"uid"),Line));
118       F.write("=%s %s" % (GetAttr(x,"uidNumber"),Line));
119       I = I + 1;
120
121   # Oops, something unspeakable happened.
122   except:
123    Die(File,None,F);
124    raise;
125   Done(File,None,F);
126
127 # Generate the shadow list
128 def GenShadow(l,File):
129   F = None;
130   try:
131    OldMask = os.umask(0077);
132    F = open(File + ".tdb.tmp","w",0600);
133    os.umask(OldMask);
134
135    # Fetch all the users
136    global PasswdAttrs;
137    if PasswdAttrs == None:
138       raise "No Users";
139
140    I = 0;
141    for x in PasswdAttrs:
142       if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
143          continue;
144          
145       Pass = GetAttr(x,"userPassword");
146       if Pass[0:7] != "{crypt}" or len(Pass) > 50:
147          Pass = '*';
148       else:
149          Pass = Pass[7:];
150       Line = "%s:%s:%s:%s:%s:%s:%s:%s:" % (GetAttr(x,"uid"),\
151               Pass,GetAttr(x,"shadowLastChange"),\
152               GetAttr(x,"shadowMin"),GetAttr(x,"shadowMax"),\
153               GetAttr(x,"shadowWarning"),GetAttr(x,"shadowinactive"),\
154               GetAttr(x,"shadowexpire"));
155       Line = Sanitize(Line) + "\n";
156       F.write("0%u %s" % (I,Line));
157       F.write(".%s %s" % (GetAttr(x,"uid"),Line));
158       I = I + 1;
159
160   # Oops, something unspeakable happened.
161   except:
162    Die(File,None,F);
163    raise;
164   Done(File,None,F);
165
166 # Generate the shadow list
167 def GenSSHShadow(l,File):
168   F = None;
169   try:
170    OldMask = os.umask(0077);
171    F = open(File + ".tmp","w",0600);
172    os.umask(OldMask);
173
174    # Fetch all the users
175    global PasswdAttrs;
176    if PasswdAttrs == None:
177       raise "No Users";
178
179    for x in PasswdAttrs:
180       # If the account is locked, do not write it.
181       # This is a partial stop-gap. The ssh also needs to change this
182       # to ignore ~/.ssh/authorized* files.
183       if (string.find(GetAttr(x,"userPassword"),"*LK*")  != -1):
184          continue;
185
186       if x[1].has_key("uidNumber") == 0 or \
187          x[1].has_key("sshRSAAuthKey") == 0:
188          continue;
189       for I in x[1]["sshRSAAuthKey"]:
190          User = GetAttr(x,"uid");
191          Line = "%s: %s" %(User,I);
192          Line = Sanitize(Line) + "\n";
193          F.write(Line);
194   # Oops, something unspeakable happened.
195   except:
196    Die(File,F,None);
197    raise;
198   Done(File,F,None);
199
200 # Generate the group list
201 def GenGroup(l,File):
202   F = None;
203   try:
204    F = open(File + ".tdb.tmp","w");
205
206    # Generate the GroupMap
207    GroupMap = {};
208    for x in GroupIDMap.keys():
209       GroupMap[x] = [];
210       
211    # Fetch all the users
212    global PasswdAttrs;
213    if PasswdAttrs == None:
214       raise "No Users";
215
216    # Sort them into a list of groups having a set of users
217    for x in PasswdAttrs:
218       if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
219          continue;
220       if x[1].has_key("supplementaryGid") == 0:
221          continue;
222          
223       for I in x[1]["supplementaryGid"]:
224          if GroupMap.has_key(I):
225             GroupMap[I].append(GetAttr(x,"uid"));
226          else:
227             print "Group does not exist ",I,"but",GetAttr(x,"uid"),"is in it";
228             
229    # Output the group file.
230    J = 0;
231    for x in GroupMap.keys():
232       if GroupIDMap.has_key(x) == 0:
233          continue;
234       Line = "%s:x:%u:" % (x,GroupIDMap[x]);
235       Comma = '';
236       for I in GroupMap[x]:
237         Line = Line + ("%s%s" % (Comma,I));
238         Comma = ',';
239       Line = Sanitize(Line) + "\n";
240       F.write("0%u %s" % (J,Line));
241       F.write(".%s %s" % (x,Line));
242       F.write("=%u %s" % (GroupIDMap[x],Line));
243       J = J + 1;
244       
245   # Oops, something unspeakable happened.
246   except:
247    Die(File,None,F);
248    raise;
249   Done(File,None,F);
250
251 # Generate the email forwarding list
252 def GenForward(l,File):
253   F = None;
254   Fdb = None;
255   try:
256    OldMask = os.umask(0022);
257    F = open(File + ".tmp","w",0644);
258    os.umask(OldMask);
259
260    # Fetch all the users
261    global PasswdAttrs;
262    if PasswdAttrs == None:
263       raise "No Users";
264
265    # Write out the email address for each user
266    for x in PasswdAttrs:
267       if x[1].has_key("emailForward") == 0 or IsInGroup(x) == 0:
268          continue;
269       
270       # Do not allow people to try to buffer overflow busted parsers
271       if len(GetAttr(x,"emailForward")) > 200:
272          continue;
273
274       # Check the forwarding address
275       if EmailCheck.match(GetAttr(x,"emailForward")) == None:
276          continue;
277       Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailForward"));
278       Line = Sanitize(Line) + "\n";
279       F.write(Line);
280       
281   # Oops, something unspeakable happened.
282   except:
283    Die(File,F,Fdb);
284    raise;
285   Done(File,F,Fdb);
286
287 def GenAllForward(l,File):
288   Fdb = None;
289   try:
290    OldMask = os.umask(0022);
291    Fdb = os.popen("cdbmake %s %s.tmp"%(File,File),"w");
292    os.umask(OldMask);
293
294    # Fetch all the users
295    global PasswdAttrs;
296    if PasswdAttrs == None:
297       raise "No Users";
298
299    # Write out the email address for each user
300    for x in PasswdAttrs:
301       if x[1].has_key("emailForward") == 0:
302          continue;
303       
304       # Do not allow people to try to buffer overflow busted parsers
305       Forward = GetAttr(x,"emailForward");
306       if len(Forward) > 200:
307          continue;
308
309       # Check the forwarding address
310       if EmailCheck.match(Forward) == None:
311          continue;
312          
313       User = GetAttr(x,"uid");
314       Fdb.write("+%d,%d:%s->%s\n"%(len(User),len(Forward),User,Forward));
315    Fdb.write("\n");
316   # Oops, something unspeakable happened.
317   except:
318     Fdb.close();
319     raise;
320   if Fdb.close() != None:
321     raise "cdbmake gave an error";
322
323 # Generate the anon XEarth marker file 
324 def GenMarkers(l,File):
325   F = None;
326   Fdb = None;
327   try:
328    F = open(File + ".tmp","w");
329    Fdb = None;
330
331    # Fetch all the users
332    global PasswdAttrs;
333    if PasswdAttrs == None:
334       raise "No Users";
335
336    # Write out the position for each user
337    for x in PasswdAttrs:
338       if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
339          continue;       
340       try:
341          Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
342          Line = Sanitize(Line) + "\n";
343          F.write(Line);
344       except:
345          pass;
346       
347   # Oops, something unspeakable happened.
348   except:
349    Die(File,F,Fdb);
350    raise;
351   Done(File,F,Fdb);
352
353 # Generate the debian-private subscription list
354 def GenPrivate(l,File):
355   F = None;
356   Fdb = None;
357   try:
358    F = open(File + ".tmp","w");
359    Fdb = None;
360
361    # Fetch all the users
362    global PasswdAttrs;
363    if PasswdAttrs == None:
364       raise "No Users";
365
366    # Write out the position for each user
367    for x in PasswdAttrs:
368       if x[1].has_key("privateSub") == 0:
369          continue;
370
371       # If the account is locked, do not write it
372       if (string.find(GetAttr(x,"userPassword"),"*LK*")  != -1):
373          continue;
374
375       # If the account has no PGP key, do not write it
376       if x[1].has_key("keyFingerPrint") == 0:
377          continue;
378
379       # Must be in the Debian group (yuk, hard coded for now)
380       if GetAttr(x,"gidNumber") != "800":
381          continue;
382
383       try:
384          Line = "%s"%(GetAttr(x,"privateSub"));
385          Line = Sanitize(Line) + "\n";
386          F.write(Line);
387       except:
388          pass;
389       
390   # Oops, something unspeakable happened.
391   except:
392    Die(File,F,Fdb);
393    raise;
394   Done(File,F,Fdb);
395
396 # Generate the DNS Zone file
397 def GenDNS(l,File,HomePrefix):
398   F = None;
399   try:
400    F = open(File + ".tmp","w");
401    
402    # Fetch all the users
403    global PasswdAttrs;
404    if PasswdAttrs == None:
405       raise "No Users";
406
407    # Write out the zone file entry for each user
408    for x in PasswdAttrs:
409       if x[1].has_key("dnsZoneEntry") == 0:
410          continue;
411       try:
412          F.write("; %s\n"%(EmailAddress(x)));
413          for z in x[1]["dnsZoneEntry"]:
414             Split = string.split(string.lower(z));
415             if string.lower(Split[1]) == 'in':
416                for y in range(0,len(Split)):
417                   if Split[y] == "$":
418                      Split[y] = "\n\t";
419                Line = string.join(Split," ") + "\n";
420                F.write(Line);
421                
422                Host = Split[0] + DNSZone;
423                if BSMTPCheck.match(Line) != None:
424                    F.write("; Has BSMTP\n");
425                                
426                # Write some identification information
427                if string.lower(Split[2]) == "a":
428                   Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
429                   for y in x[1]["keyFingerPrint"]:
430                      Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
431                   F.write(Line);
432             else:
433                Line = "; Err %s"%(str(Split));
434                F.write(Line);
435
436          F.write("\n");
437       except:
438          F.write("; Errors\n");
439          pass;
440       
441   # Oops, something unspeakable happened.
442   except:
443    Die(File,F,None);
444    raise;
445   Done(File,F,None);
446
447 # Generate the BSMTP file
448 def GenBSMTP(l,File,HomePrefix):
449   F = None;
450   try:
451    F = open(File + ".tmp","w");
452    
453    # Fetch all the users
454    global PasswdAttrs;
455    if PasswdAttrs == None:
456       raise "No Users";
457
458    # Write out the zone file entry for each user
459    for x in PasswdAttrs:
460       if x[1].has_key("dnsZoneEntry") == 0:
461          continue;
462       try:
463          for z in x[1]["dnsZoneEntry"]:
464             Split = string.split(string.lower(z));
465             if string.lower(Split[1]) == 'in':
466                for y in range(0,len(Split)):
467                   if Split[y] == "$":
468                      Split[y] = "\n\t";
469                Line = string.join(Split," ") + "\n";
470                
471                Host = Split[0] + DNSZone;
472                if BSMTPCheck.match(Line) != None:
473                    F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
474                                GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
475                                
476       except:
477          F.write("; Errors\n");
478          pass;
479       
480   # Oops, something unspeakable happened.
481   except:
482    Die(File,F,None);
483    raise;
484   Done(File,F,None);
485
486 # Generate the ssh known hosts file
487 def GenSSHKnown(l,File):
488   F = None;
489   try:
490    OldMask = os.umask(0022);
491    F = open(File + ".tmp","w",0644);
492    os.umask(OldMask);
493
494    # Fetch all the hosts
495    HostKeys = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
496                 ["hostname","sshRSAHostKey"]);
497    
498    if HostKeys == None:
499       raise "No Hosts";
500
501    for x in HostKeys:
502       if x[1].has_key("hostname") == 0 or \
503          x[1].has_key("sshRSAHostKey") == 0:
504          continue;
505       Host = GetAttr(x,"hostname");
506       SHost = string.find(Host,".");
507       for I in x[1]["sshRSAHostKey"]:
508          if SHost == None:
509             Line = "%s,%s %s" %(Host,socket.gethostbyname(Host),I);
510          else:
511             Line = "%s,%s,%s %s" %(Host,Host[0:SHost],socket.gethostbyname(Host),I);
512          Line = Sanitize(Line) + "\n";
513          F.write(Line);
514   # Oops, something unspeakable happened.
515   except:
516    Die(File,F,None);
517    raise;
518   Done(File,F,None);
519
520 # Generate the debianhosts file (list of all IP addresses)
521 def GenHosts(l,File):
522   F = None;
523   try:
524    OldMask = os.umask(0022);
525    F = open(File + ".tmp","w",0644);
526    os.umask(OldMask);
527
528    # Fetch all the hosts
529    HostNames = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"hostname=*",\
530                 ["hostname"]);
531    
532    if HostNames == None:
533       raise "No Hosts";
534
535    for x in HostNames:
536       if x[1].has_key("hostname") == 0:
537          continue;
538       Host = GetAttr(x,"hostname");
539       Addr = socket.gethostbyname(Host);
540       F.write(Addr + "\n");
541   # Oops, something unspeakable happened.
542   except:
543    Die(File,F,None);
544    raise;
545   Done(File,F,None);
546
547 # Connect to the ldap server
548 l = ldap.open(LDAPServer);
549 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
550 Pass = string.split(string.strip(F.readline())," ");
551 F.close();
552 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
553
554 # Fetch all the groups
555 GroupIDMap = {};
556 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
557                   ["gid","gidNumber"]);
558
559 # Generate the GroupMap and GroupIDMap
560 for x in Attrs:
561    if x[1].has_key("gidNumber") == 0:
562       continue;
563    GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
564
565 # Fetch all the users
566 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
567                 ["uid","uidNumber","gidNumber","supplementaryGid",\
568                  "gecos","loginShell","userPassword","shadowLastChange",\
569                  "shadowMin","shadowMax","shadowWarning","shadowinactive",
570                  "shadowexpire","emailForward","latitude","longitude",\
571                  "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
572                  "keyFingerPrint","privateSub"]);
573
574 # Open the control file
575 if len(sys.argv) == 1:
576    F = open(GenerateConf,"r");
577 else:
578    F = open(sys.argv[1],"r")
579
580 # Generate global things
581 GlobalDir = GenerateDir+"/";
582 GenSSHShadow(l,GlobalDir+"ssh-rsa-shadow");
583 GenAllForward(l,GlobalDir+"mail-forward.cdb");
584 GenMarkers(l,GlobalDir+"markers");
585 GenPrivate(l,GlobalDir+"debian-private");
586 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
587 GenHosts(l,GlobalDir+"debianhosts");
588
589 # Compatibility.
590 GenForward(l,GlobalDir+"forward-alias");
591    
592 while(1):
593    Line = F.readline();
594    if Line == "":
595       break;
596    Line = string.strip(Line);
597    if Line == "":
598       continue;
599    if Line[0] == '#':
600       continue;
601
602    Split = string.split(Line," ");
603    OutDir = GenerateDir + '/' + Split[0] + '/';
604    try: os.mkdir(OutDir);
605    except: pass;
606
607    # Get the group list and convert any named groups to numerics
608    GroupList = {};
609    ExtraList = {};
610    for I in Split[2:]:
611       if I[0] == '[':
612          ExtraList[I] = None;
613          continue;
614       GroupList[I] = None;
615       if GroupIDMap.has_key(I):
616          GroupList[str(GroupIDMap[I])] = None;
617
618    Allowed = GroupList;
619    if Allowed == {}:
620      Allowed = None
621    CurrentHost = Split[0];
622
623    sys.stdout.flush();
624    GenPasswd(l,OutDir+"passwd",Split[1]);
625    sys.stdout.flush();
626    GenGroup(l,OutDir+"group");
627    if ExtraList.has_key("[UNTRUSTED]"):
628         continue;
629    GenShadow(l,OutDir+"shadow");
630         
631    # Link in global things   
632    DoLink(GlobalDir,OutDir,"ssh-rsa-shadow");
633    DoLink(GlobalDir,OutDir,"markers");
634    DoLink(GlobalDir,OutDir,"mail-forward.cdb");
635    DoLink(GlobalDir,OutDir,"ssh_known_hosts");
636    DoLink(GlobalDir,OutDir,"debianhosts");
637
638    # Compatibility.
639    DoLink(GlobalDir,OutDir,"forward-alias");
640
641    if ExtraList.has_key("[DNS]"):
642       GenDNS(l,OutDir+"dns-zone",Split[1]);
643       
644    if ExtraList.has_key("[BSMTP]"):
645       GenBSMTP(l,OutDir+"bsmtp",Split[1]);
646
647    if ExtraList.has_key("[PRIVATE]"):
648       DoLink(GlobalDir,OutDir,"debian-private");
649