add dns-sshfp file containing SSHFP DNS records for each host.
[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  Joey Schulze <joey@infodrom.org>
8 #   Copyright (c) 2001-2006  Ryan Murray <rmurray@debian.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, base64, sha;
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 (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 DNS SSHFP records
452 def GenSSHFP(l,File,HomePrefix):
453   F = None
454   try:
455    F = open(File + ".tmp","w")
456    
457    # Fetch all the hosts
458    global HostAttrs
459    if HostAttrs == None:
460       raise "No Hosts"
461
462    for x in HostAttrs:
463       if x[1].has_key("hostname") == 0 or \
464          x[1].has_key("sshRSAHostKey") == 0:
465          continue
466       Host = GetAttr(x,"hostname");
467       Algorithm = None
468       for I in x[1]["sshRSAHostKey"]:
469          Split = string.split(I)
470          if Split[0] == 'ssh-rsa':
471             Algorithm = 1
472          if Split[0] == 'ssh-dss':
473             Algorithm = 2
474          if Algorithm == None:
475             continue
476          Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
477          Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
478          Line = Sanitize(Line) + "\n"
479          F.write(Line)
480   # Oops, something unspeakable happened.
481   except:
482    Die(File,F,None)
483    raise;
484   Done(File,F,None)
485
486 # Generate the BSMTP file
487 def GenBSMTP(l,File,HomePrefix):
488   F = None;
489   try:
490    F = open(File + ".tmp","w");
491    
492    # Fetch all the users
493    global PasswdAttrs;
494    if PasswdAttrs == None:
495       raise "No Users";
496
497    # Write out the zone file entry for each user
498    for x in PasswdAttrs:
499       if x[1].has_key("dnsZoneEntry") == 0:
500          continue;
501
502       # If the account has no PGP key, do not write it
503       if x[1].has_key("keyFingerPrint") == 0:
504          continue;
505       try:
506          for z in x[1]["dnsZoneEntry"]:
507             Split = string.split(string.lower(z));
508             if string.lower(Split[1]) == 'in':
509                for y in range(0,len(Split)):
510                   if Split[y] == "$":
511                      Split[y] = "\n\t";
512                Line = string.join(Split," ") + "\n";
513                
514                Host = Split[0] + DNSZone;
515                if BSMTPCheck.match(Line) != None:
516                    F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
517                                GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
518                                
519       except:
520          F.write("; Errors\n");
521          pass;
522       
523   # Oops, something unspeakable happened.
524   except:
525    Die(File,F,None);
526    raise;
527   Done(File,F,None);
528
529 # Generate the ssh known hosts file
530 def GenSSHKnown(l,File):
531   F = None;
532   try:
533    OldMask = os.umask(0022);
534    F = open(File + ".tmp","w",0644);
535    os.umask(OldMask);
536
537    global HostAttrs
538    if HostAttrs == None:
539       raise "No Hosts";
540    
541    for x in HostAttrs:
542       if x[1].has_key("hostname") == 0 or \
543          x[1].has_key("sshRSAHostKey") == 0:
544          continue;
545       Host = GetAttr(x,"hostname");
546       SHost = string.find(Host,".");
547       for I in x[1]["sshRSAHostKey"]:
548          if SHost == None:
549             Line = "%s,%s %s" %(Host,socket.gethostbyname(Host),I);
550          else:
551             Line = "%s,%s,%s %s" %(Host,Host[0:SHost],socket.gethostbyname(Host),I);
552          Line = Sanitize(Line) + "\n";
553          F.write(Line);
554   # Oops, something unspeakable happened.
555   except:
556    Die(File,F,None);
557    raise;
558   Done(File,F,None);
559
560 # Generate the debianhosts file (list of all IP addresses)
561 def GenHosts(l,File):
562   F = None;
563   try:
564    OldMask = os.umask(0022);
565    F = open(File + ".tmp","w",0644);
566    os.umask(OldMask);
567
568    # Fetch all the hosts
569    HostNames = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"hostname=*",\
570                 ["hostname"]);
571    
572    if HostNames == None:
573       raise "No Hosts";
574
575    for x in HostNames:
576       if x[1].has_key("hostname") == 0:
577          continue;
578       Host = GetAttr(x,"hostname");
579       try:
580         Addr = socket.gethostbyname(Host);
581         F.write(Addr + "\n");
582       except:
583         pass
584   # Oops, something unspeakable happened.
585   except:
586    Die(File,F,None);
587    raise;
588   Done(File,F,None);
589
590 # Connect to the ldap server
591 l = ldap.open(LDAPServer);
592 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
593 Pass = string.split(string.strip(F.readline())," ");
594 F.close();
595 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
596
597 # Fetch all the groups
598 GroupIDMap = {};
599 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
600                   ["gid","gidNumber"]);
601
602 # Generate the GroupMap and GroupIDMap
603 for x in Attrs:
604    if x[1].has_key("gidNumber") == 0:
605       continue;
606    GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
607
608 # Fetch all the users
609 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
610                 ["uid","uidNumber","gidNumber","supplementaryGid",\
611                  "gecos","loginShell","userPassword","shadowLastChange",\
612                  "shadowMin","shadowMax","shadowWarning","shadowinactive",
613                  "shadowexpire","emailForward","latitude","longitude",\
614                  "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
615                  "keyFingerPrint","privateSub"]);
616 # Fetch all the hosts
617 HostAttrs    = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
618                 ["hostname","sshRSAHostKey"]);
619
620 # Open the control file
621 if len(sys.argv) == 1:
622    F = open(GenerateConf,"r");
623 else:
624    F = open(sys.argv[1],"r")
625
626 # Generate global things
627 GlobalDir = GenerateDir+"/";
628 GenSSHShadow(l,GlobalDir+"ssh-rsa-shadow");
629 GenAllForward(l,GlobalDir+"mail-forward.cdb");
630 GenMarkers(l,GlobalDir+"markers");
631 GenPrivate(l,GlobalDir+"debian-private");
632 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
633 GenHosts(l,GlobalDir+"debianhosts");
634
635 # Compatibility.
636 GenForward(l,GlobalDir+"forward-alias");
637    
638 while(1):
639    Line = F.readline();
640    if Line == "":
641       break;
642    Line = string.strip(Line);
643    if Line == "":
644       continue;
645    if Line[0] == '#':
646       continue;
647
648    Split = string.split(Line," ");
649    OutDir = GenerateDir + '/' + Split[0] + '/';
650    try: os.mkdir(OutDir);
651    except: pass;
652
653    # Get the group list and convert any named groups to numerics
654    GroupList = {};
655    ExtraList = {};
656    for I in Split[2:]:
657       if I[0] == '[':
658          ExtraList[I] = None;
659          continue;
660       GroupList[I] = None;
661       if GroupIDMap.has_key(I):
662          GroupList[str(GroupIDMap[I])] = None;
663
664    Allowed = GroupList;
665    if Allowed == {}:
666      Allowed = None
667    CurrentHost = Split[0];
668
669    sys.stdout.flush();
670    GenPasswd(l,OutDir+"passwd",Split[1]);
671    sys.stdout.flush();
672    GenGroup(l,OutDir+"group");
673    if ExtraList.has_key("[UNTRUSTED]"):
674         continue;
675    GenShadow(l,OutDir+"shadow");
676         
677    # Link in global things   
678    DoLink(GlobalDir,OutDir,"ssh-rsa-shadow");
679    DoLink(GlobalDir,OutDir,"markers");
680    DoLink(GlobalDir,OutDir,"mail-forward.cdb");
681    DoLink(GlobalDir,OutDir,"ssh_known_hosts");
682    DoLink(GlobalDir,OutDir,"debianhosts");
683
684    # Compatibility.
685    DoLink(GlobalDir,OutDir,"forward-alias");
686
687    if ExtraList.has_key("[DNS]"):
688       GenDNS(l,OutDir+"dns-zone",Split[1]);
689       GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
690       
691    if ExtraList.has_key("[BSMTP]"):
692       GenBSMTP(l,OutDir+"bsmtp",Split[1])
693
694    if ExtraList.has_key("[PRIVATE]"):
695       DoLink(GlobalDir,OutDir,"debian-private")