Don't let Python abort unconditionally if a host wasn't found.
[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
412       # If the account has no PGP key, do not write it
413       if x[1].has_key("keyFingerPrint") == 0:
414          continue;
415       try:
416          F.write("; %s\n"%(EmailAddress(x)));
417          for z in x[1]["dnsZoneEntry"]:
418             Split = string.split(string.lower(z));
419             if string.lower(Split[1]) == 'in':
420                for y in range(0,len(Split)):
421                   if Split[y] == "$":
422                      Split[y] = "\n\t";
423                Line = string.join(Split," ") + "\n";
424                F.write(Line);
425                
426                Host = Split[0] + DNSZone;
427                if BSMTPCheck.match(Line) != None:
428                    F.write("; Has BSMTP\n");
429                                
430                # Write some identification information
431                if string.lower(Split[2]) == "a":
432                   Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
433                   for y in x[1]["keyFingerPrint"]:
434                      Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
435                   F.write(Line);
436             else:
437                Line = "; Err %s"%(str(Split));
438                F.write(Line);
439
440          F.write("\n");
441       except:
442          F.write("; Errors\n");
443          pass;
444       
445   # Oops, something unspeakable happened.
446   except:
447    Die(File,F,None);
448    raise;
449   Done(File,F,None);
450
451 # Generate the BSMTP file
452 def GenBSMTP(l,File,HomePrefix):
453   F = None;
454   try:
455    F = open(File + ".tmp","w");
456    
457    # Fetch all the users
458    global PasswdAttrs;
459    if PasswdAttrs == None:
460       raise "No Users";
461
462    # Write out the zone file entry for each user
463    for x in PasswdAttrs:
464       if x[1].has_key("dnsZoneEntry") == 0:
465          continue;
466
467       # If the account has no PGP key, do not write it
468       if x[1].has_key("keyFingerPrint") == 0:
469          continue;
470       try:
471          for z in x[1]["dnsZoneEntry"]:
472             Split = string.split(string.lower(z));
473             if string.lower(Split[1]) == 'in':
474                for y in range(0,len(Split)):
475                   if Split[y] == "$":
476                      Split[y] = "\n\t";
477                Line = string.join(Split," ") + "\n";
478                
479                Host = Split[0] + DNSZone;
480                if BSMTPCheck.match(Line) != None:
481                    F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
482                                GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
483                                
484       except:
485          F.write("; Errors\n");
486          pass;
487       
488   # Oops, something unspeakable happened.
489   except:
490    Die(File,F,None);
491    raise;
492   Done(File,F,None);
493
494 # Generate the ssh known hosts file
495 def GenSSHKnown(l,File):
496   F = None;
497   try:
498    OldMask = os.umask(0022);
499    F = open(File + ".tmp","w",0644);
500    os.umask(OldMask);
501
502    # Fetch all the hosts
503    HostKeys = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
504                 ["hostname","sshRSAHostKey"]);
505    
506    if HostKeys == None:
507       raise "No Hosts";
508
509    for x in HostKeys:
510       if x[1].has_key("hostname") == 0 or \
511          x[1].has_key("sshRSAHostKey") == 0:
512          continue;
513       Host = GetAttr(x,"hostname");
514       SHost = string.find(Host,".");
515       for I in x[1]["sshRSAHostKey"]:
516          if SHost == None:
517             Line = "%s,%s %s" %(Host,socket.gethostbyname(Host),I);
518          else:
519             Line = "%s,%s,%s %s" %(Host,Host[0:SHost],socket.gethostbyname(Host),I);
520          Line = Sanitize(Line) + "\n";
521          F.write(Line);
522   # Oops, something unspeakable happened.
523   except:
524    Die(File,F,None);
525    raise;
526   Done(File,F,None);
527
528 # Generate the debianhosts file (list of all IP addresses)
529 def GenHosts(l,File):
530   F = None;
531   try:
532    OldMask = os.umask(0022);
533    F = open(File + ".tmp","w",0644);
534    os.umask(OldMask);
535
536    # Fetch all the hosts
537    HostNames = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"hostname=*",\
538                 ["hostname"]);
539    
540    if HostNames == None:
541       raise "No Hosts";
542
543    for x in HostNames:
544       if x[1].has_key("hostname") == 0:
545          continue;
546       Host = GetAttr(x,"hostname");
547       try:
548         Addr = socket.gethostbyname(Host);
549         F.write(Addr + "\n");
550       except:
551         pass
552   # Oops, something unspeakable happened.
553   except:
554    Die(File,F,None);
555    raise;
556   Done(File,F,None);
557
558 # Connect to the ldap server
559 l = ldap.open(LDAPServer);
560 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
561 Pass = string.split(string.strip(F.readline())," ");
562 F.close();
563 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
564
565 # Fetch all the groups
566 GroupIDMap = {};
567 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
568                   ["gid","gidNumber"]);
569
570 # Generate the GroupMap and GroupIDMap
571 for x in Attrs:
572    if x[1].has_key("gidNumber") == 0:
573       continue;
574    GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
575
576 # Fetch all the users
577 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
578                 ["uid","uidNumber","gidNumber","supplementaryGid",\
579                  "gecos","loginShell","userPassword","shadowLastChange",\
580                  "shadowMin","shadowMax","shadowWarning","shadowinactive",
581                  "shadowexpire","emailForward","latitude","longitude",\
582                  "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
583                  "keyFingerPrint","privateSub"]);
584
585 # Open the control file
586 if len(sys.argv) == 1:
587    F = open(GenerateConf,"r");
588 else:
589    F = open(sys.argv[1],"r")
590
591 # Generate global things
592 GlobalDir = GenerateDir+"/";
593 GenSSHShadow(l,GlobalDir+"ssh-rsa-shadow");
594 GenAllForward(l,GlobalDir+"mail-forward.cdb");
595 GenMarkers(l,GlobalDir+"markers");
596 GenPrivate(l,GlobalDir+"debian-private");
597 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
598 GenHosts(l,GlobalDir+"debianhosts");
599
600 # Compatibility.
601 GenForward(l,GlobalDir+"forward-alias");
602    
603 while(1):
604    Line = F.readline();
605    if Line == "":
606       break;
607    Line = string.strip(Line);
608    if Line == "":
609       continue;
610    if Line[0] == '#':
611       continue;
612
613    Split = string.split(Line," ");
614    OutDir = GenerateDir + '/' + Split[0] + '/';
615    try: os.mkdir(OutDir);
616    except: pass;
617
618    # Get the group list and convert any named groups to numerics
619    GroupList = {};
620    ExtraList = {};
621    for I in Split[2:]:
622       if I[0] == '[':
623          ExtraList[I] = None;
624          continue;
625       GroupList[I] = None;
626       if GroupIDMap.has_key(I):
627          GroupList[str(GroupIDMap[I])] = None;
628
629    Allowed = GroupList;
630    if Allowed == {}:
631      Allowed = None
632    CurrentHost = Split[0];
633
634    sys.stdout.flush();
635    GenPasswd(l,OutDir+"passwd",Split[1]);
636    sys.stdout.flush();
637    GenGroup(l,OutDir+"group");
638    if ExtraList.has_key("[UNTRUSTED]"):
639         continue;
640    GenShadow(l,OutDir+"shadow");
641         
642    # Link in global things   
643    DoLink(GlobalDir,OutDir,"ssh-rsa-shadow");
644    DoLink(GlobalDir,OutDir,"markers");
645    DoLink(GlobalDir,OutDir,"mail-forward.cdb");
646    DoLink(GlobalDir,OutDir,"ssh_known_hosts");
647    DoLink(GlobalDir,OutDir,"debianhosts");
648
649    # Compatibility.
650    DoLink(GlobalDir,OutDir,"forward-alias");
651
652    if ExtraList.has_key("[DNS]"):
653       GenDNS(l,OutDir+"dns-zone",Split[1]);
654       
655    if ExtraList.has_key("[BSMTP]"):
656       GenBSMTP(l,OutDir+"bsmtp",Split[1]);
657
658    if ExtraList.has_key("[PRIVATE]"):
659       DoLink(GlobalDir,OutDir,"debian-private");
660