3 # Generates passwd, shadow and group files from the ldap directory.
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>
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.
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.
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.
24 import string, re, time, ldap, getopt, sys, os, pwd, posix, socket, base64, sha
25 from userdir_ldap import *;
35 EmailCheck = re.compile("^([^ <>@]+@[^ ,<>@]+)?$");
36 BSMTPCheck = re.compile(".*mx 0 (gluck)\.debian\.org\..*",re.DOTALL);
37 DNSZone = ".debian.net"
40 return string.translate(Str,string.maketrans("\n\r\t","$$$"));
42 def DoLink(From,To,File):
43 try: posix.remove(To+File);
45 posix.link(From+File,To+File);
47 # See if this user is in the group list
48 def IsInGroup(DnRecord):
52 # See if the primary group is in the list
53 if Allowed.has_key(GetAttr(DnRecord,"gidNumber")) != 0:
56 # Check the host based ACL
57 if DnRecord[1].has_key("allowedHost") != 0:
58 for I in DnRecord[1]["allowedHost"]:
62 # See if there are supplementary groups
63 if DnRecord[1].has_key("supplementaryGid") == 0:
66 # Check the supplementary groups
67 for I in DnRecord[1]["supplementaryGid"]:
68 if Allowed.has_key(I):
77 try: os.remove(File + ".tmp");
79 try: os.remove(File + ".tdb.tmp");
85 os.rename(File + ".tmp",File);
88 os.rename(File + ".tdb.tmp",File+".tdb");
90 # Generate the password list
91 def GenPasswd(l,File,HomePrefix):
94 F = open(File + ".tdb.tmp","w");
98 if PasswdAttrs == None:
102 for x in PasswdAttrs:
103 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
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:
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"));
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));
121 # Oops, something unspeakable happened.
127 # Generate the shadow list
128 def GenShadow(l,File):
131 OldMask = os.umask(0077);
132 F = open(File + ".tdb.tmp","w",0600);
135 # Fetch all the users
137 if PasswdAttrs == None:
141 for x in PasswdAttrs:
142 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
145 Pass = GetAttr(x,"userPassword");
146 if Pass[0:7] != "{crypt}" or len(Pass) > 50:
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));
160 # Oops, something unspeakable happened.
166 # Generate the shadow list
167 def GenSSHShadow(l,File):
170 OldMask = os.umask(0077);
171 F = open(File + ".tmp","w",0600);
174 # Fetch all the users
176 if PasswdAttrs == None:
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 or GetAttr(x,"userPassword").startswith("!"):
187 if x[1].has_key("uidNumber") == 0 or \
188 x[1].has_key("sshRSAAuthKey") == 0:
190 for I in x[1]["sshRSAAuthKey"]:
191 User = GetAttr(x,"uid");
192 Line = "%s: %s" %(User,I);
193 Line = Sanitize(Line) + "\n";
195 # Oops, something unspeakable happened.
201 # Generate the group list
202 def GenGroup(l,File):
205 F = open(File + ".tdb.tmp","w");
207 # Generate the GroupMap
209 for x in GroupIDMap.keys():
212 # Fetch all the users
214 if PasswdAttrs == None:
217 # Sort them into a list of groups having a set of users
218 for x in PasswdAttrs:
219 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
221 if x[1].has_key("supplementaryGid") == 0:
224 for I in x[1]["supplementaryGid"]:
225 if GroupMap.has_key(I):
226 GroupMap[I].append(GetAttr(x,"uid"));
228 print "Group does not exist ",I,"but",GetAttr(x,"uid"),"is in it";
230 # Output the group file.
232 for x in GroupMap.keys():
233 if GroupIDMap.has_key(x) == 0:
235 Line = "%s:x:%u:" % (x,GroupIDMap[x]);
237 for I in GroupMap[x]:
238 Line = Line + ("%s%s" % (Comma,I));
240 Line = Sanitize(Line) + "\n";
241 F.write("0%u %s" % (J,Line));
242 F.write(".%s %s" % (x,Line));
243 F.write("=%u %s" % (GroupIDMap[x],Line));
246 # Oops, something unspeakable happened.
252 # Generate the email forwarding list
253 def GenForward(l,File):
256 OldMask = os.umask(0022);
257 F = open(File + ".tmp","w",0644);
260 # Fetch all the users
262 if PasswdAttrs == None:
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:
270 # Do not allow people to try to buffer overflow busted parsers
271 if len(GetAttr(x,"emailForward")) > 200:
274 # Check the forwarding address
275 if EmailCheck.match(GetAttr(x,"emailForward")) == None:
277 Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailForward"));
278 Line = Sanitize(Line) + "\n";
281 # Oops, something unspeakable happened.
287 def GenAllForward(l,File):
290 OldMask = os.umask(0022);
291 Fdb = os.popen("cdbmake %s %s.tmp"%(File,File),"w");
294 # Fetch all the users
296 if PasswdAttrs == None:
299 # Write out the email address for each user
300 for x in PasswdAttrs:
301 if x[1].has_key("emailForward") == 0:
304 # Do not allow people to try to buffer overflow busted parsers
305 Forward = GetAttr(x,"emailForward");
306 if len(Forward) > 200:
309 # Check the forwarding address
310 if EmailCheck.match(Forward) == None:
313 User = GetAttr(x,"uid");
314 Fdb.write("+%d,%d:%s->%s\n"%(len(User),len(Forward),User,Forward));
316 # Oops, something unspeakable happened.
320 if Fdb.close() != None:
321 raise "cdbmake gave an error";
323 # Generate the anon XEarth marker file
324 def GenMarkers(l,File):
327 F = open(File + ".tmp","w");
329 # Fetch all the users
331 if PasswdAttrs == None:
334 # Write out the position for each user
335 for x in PasswdAttrs:
336 if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
339 Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
340 Line = Sanitize(Line) + "\n";
345 # Oops, something unspeakable happened.
351 # Generate the debian-private subscription list
352 def GenPrivate(l,File):
355 F = open(File + ".tmp","w");
357 # Fetch all the users
359 if PasswdAttrs == None:
362 # Write out the position for each user
363 for x in PasswdAttrs:
364 if x[1].has_key("privateSub") == 0:
367 # If the account is locked, do not write it
368 if (string.find(GetAttr(x,"userPassword"),"*LK*") != -1) \
369 or GetAttr(x,"userPassword").startswith("!"):
372 # If the account has no PGP key, do not write it
373 if x[1].has_key("keyFingerPrint") == 0:
376 # Must be in the Debian group (yuk, hard coded for now)
377 if GetAttr(x,"gidNumber") != "800":
381 Line = "%s"%(GetAttr(x,"privateSub"));
382 Line = Sanitize(Line) + "\n";
387 # Oops, something unspeakable happened.
393 # Generate the list of local addresses that refuse all mail
394 def GenMailDisable(l,File):
397 F = open(File + ".tmp","w");
399 # Fetch all the users
401 if PasswdAttrs == None:
404 for x in PasswdAttrs:
407 # If the account is locked, disable incoming mail
408 if (string.find(GetAttr(x,"userPassword"),"*LK*") != -1):
409 if GetAttr(x,"uid") == "luther":
412 Reason = "user account locked"
414 if x[1].has_key("mailDisableMessage"):
415 Reason = GetAttr(x,"mailDisableMessage")
419 # Must be in the Debian group (yuk, hard coded for now)
420 if GetAttr(x,"gidNumber") != "800":
424 Line = "%s: %s"%(GetAttr(x,"uid"),Reason);
425 Line = Sanitize(Line) + "\n";
430 # Oops, something unspeakable happened.
436 # Generate a list of uids that should have boolean affects applied
437 def GenMailBool(l,File,Key):
440 F = open(File + ".tmp","w");
442 # Fetch all the users
444 if PasswdAttrs == None:
447 for x in PasswdAttrs:
450 if x[1].has_key(Key) == 0:
453 # Must be in the Debian group (yuk, hard coded for now)
454 if GetAttr(x,"gidNumber") != "800":
457 if GetAttr(x,Key) != "TRUE":
461 Line = "%s"%(GetAttr(x,"uid"));
462 Line = Sanitize(Line) + "\n";
467 # Oops, something unspeakable happened.
473 # Generate a list of hosts for RBL or whitelist purposes.
474 def GenMailList(l,File,Key):
477 F = open(File + ".tmp","w");
479 # Fetch all the users
481 if PasswdAttrs == None:
484 for x in PasswdAttrs:
487 if x[1].has_key(Key) == 0:
490 # Must be in the Debian group (yuk, hard coded for now)
491 if GetAttr(x,"gidNumber") != "800":
498 if Key == "mailWhitelist":
499 if re.match('^[-\w.]+(/[\d]+)?$',z) == None:
502 if re.match('^[-\w.]+$',z) == None:
506 Line = GetAttr(x,"uid")
510 if Key == "mailRHSBL":
511 Line += "/$sender_address_domain"
514 Line = Sanitize(Line) + "\n";
519 # Oops, something unspeakable happened.
525 # Generate the DNS Zone file
526 def GenDNS(l,File,HomePrefix):
529 F = open(File + ".tmp","w");
531 # Fetch all the users
533 if PasswdAttrs == None:
536 # Write out the zone file entry for each user
537 for x in PasswdAttrs:
538 if x[1].has_key("dnsZoneEntry") == 0:
541 # If the account has no PGP key, do not write it
542 if x[1].has_key("keyFingerPrint") == 0:
545 F.write("; %s\n"%(EmailAddress(x)));
546 for z in x[1]["dnsZoneEntry"]:
547 Split = string.split(string.lower(z));
548 if string.lower(Split[1]) == 'in':
549 for y in range(0,len(Split)):
552 Line = string.join(Split," ") + "\n";
555 Host = Split[0] + DNSZone;
556 if BSMTPCheck.match(Line) != None:
557 F.write("; Has BSMTP\n");
559 # Write some identification information
560 if string.lower(Split[2]) == "a":
561 Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
562 for y in x[1]["keyFingerPrint"]:
563 Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
566 Line = "; Err %s"%(str(Split));
571 F.write("; Errors\n");
574 # Oops, something unspeakable happened.
580 # Generate the DNS SSHFP records
581 def GenSSHFP(l,File,HomePrefix):
584 F = open(File + ".tmp","w")
586 # Fetch all the hosts
588 if HostAttrs == None:
592 if x[1].has_key("hostname") == 0 or \
593 x[1].has_key("sshRSAHostKey") == 0:
595 Host = GetAttr(x,"hostname");
597 for I in x[1]["sshRSAHostKey"]:
598 Split = string.split(I)
599 if Split[0] == 'ssh-rsa':
601 if Split[0] == 'ssh-dss':
603 if Algorithm == None:
605 Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
606 Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
607 Line = Sanitize(Line) + "\n"
609 # Oops, something unspeakable happened.
615 # Generate the BSMTP file
616 def GenBSMTP(l,File,HomePrefix):
619 F = open(File + ".tmp","w");
621 # Fetch all the users
623 if PasswdAttrs == None:
626 # Write out the zone file entry for each user
627 for x in PasswdAttrs:
628 if x[1].has_key("dnsZoneEntry") == 0:
631 # If the account has no PGP key, do not write it
632 if x[1].has_key("keyFingerPrint") == 0:
635 for z in x[1]["dnsZoneEntry"]:
636 Split = string.split(string.lower(z));
637 if string.lower(Split[1]) == 'in':
638 for y in range(0,len(Split)):
641 Line = string.join(Split," ") + "\n";
643 Host = Split[0] + DNSZone;
644 if BSMTPCheck.match(Line) != None:
645 F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
646 GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
649 F.write("; Errors\n");
652 # Oops, something unspeakable happened.
658 # Generate the ssh known hosts file
659 def GenSSHKnown(l,File):
662 OldMask = os.umask(0022);
663 F = open(File + ".tmp","w",0644);
667 if HostAttrs == None:
671 if x[1].has_key("hostname") == 0 or \
672 x[1].has_key("sshRSAHostKey") == 0:
674 Host = GetAttr(x,"hostname");
675 SHost = string.find(Host,".");
676 for I in x[1]["sshRSAHostKey"]:
678 Line = "%s,%s %s" %(Host,socket.gethostbyname(Host),I);
680 Line = "%s,%s,%s %s" %(Host,Host[0:SHost],socket.gethostbyname(Host),I);
681 Line = Sanitize(Line) + "\n";
683 # Oops, something unspeakable happened.
689 # Generate the debianhosts file (list of all IP addresses)
690 def GenHosts(l,File):
693 OldMask = os.umask(0022);
694 F = open(File + ".tmp","w",0644);
697 # Fetch all the hosts
698 HostNames = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"hostname=*",\
701 if HostNames == None:
705 if x[1].has_key("hostname") == 0:
707 Host = GetAttr(x,"hostname");
709 Addr = socket.gethostbyname(Host);
710 F.write(Addr + "\n");
713 # Oops, something unspeakable happened.
719 # Connect to the ldap server
720 l = ldap.open(LDAPServer);
721 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
722 Pass = string.split(string.strip(F.readline())," ");
724 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
726 # Fetch all the groups
728 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
729 ["gid","gidNumber"]);
731 # Generate the GroupMap and GroupIDMap
733 if x[1].has_key("gidNumber") == 0:
735 GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
737 # Fetch all the users
738 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
739 ["uid","uidNumber","gidNumber","supplementaryGid",\
740 "gecos","loginShell","userPassword","shadowLastChange",\
741 "shadowMin","shadowMax","shadowWarning","shadowinactive",
742 "shadowexpire","emailForward","latitude","longitude",\
743 "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
744 "keyFingerPrint","privateSub","mailDisableMessage",\
745 "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
747 # Fetch all the hosts
748 HostAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
749 ["hostname","sshRSAHostKey"]);
751 # Open the control file
752 if len(sys.argv) == 1:
753 F = open(GenerateConf,"r");
755 F = open(sys.argv[1],"r")
757 # Generate global things
758 GlobalDir = GenerateDir+"/";
759 GenSSHShadow(l,GlobalDir+"ssh-rsa-shadow");
760 GenAllForward(l,GlobalDir+"mail-forward.cdb");
761 GenMarkers(l,GlobalDir+"markers");
762 GenPrivate(l,GlobalDir+"debian-private");
763 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
764 GenHosts(l,GlobalDir+"debianhosts");
765 GenMailDisable(l,GlobalDir+"mail-disable");
766 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
767 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
768 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
769 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
770 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
773 GenForward(l,GlobalDir+"forward-alias");
779 Line = string.strip(Line);
785 Split = string.split(Line," ");
786 OutDir = GenerateDir + '/' + Split[0] + '/';
787 try: os.mkdir(OutDir);
790 # Get the group list and convert any named groups to numerics
798 if GroupIDMap.has_key(I):
799 GroupList[str(GroupIDMap[I])] = None;
804 CurrentHost = Split[0];
806 DoLink(GlobalDir,OutDir,"ssh-rsa-shadow");
807 DoLink(GlobalDir,OutDir,"debianhosts");
808 DoLink(GlobalDir,OutDir,"ssh_known_hosts");
811 GenPasswd(l,OutDir+"passwd",Split[1]);
813 GenGroup(l,OutDir+"group");
814 if ExtraList.has_key("[UNTRUSTED]"):
816 if not ExtraList.has_key("[NOPASSWD]"):
817 GenShadow(l,OutDir+"shadow");
819 # Link in global things
820 DoLink(GlobalDir,OutDir,"markers");
821 DoLink(GlobalDir,OutDir,"mail-forward.cdb");
822 DoLink(GlobalDir,OutDir,"mail-disable");
823 DoLink(GlobalDir,OutDir,"mail-greylist");
824 DoLink(GlobalDir,OutDir,"mail-callout");
825 DoLink(GlobalDir,OutDir,"mail-rbl");
826 DoLink(GlobalDir,OutDir,"mail-rhsbl");
827 DoLink(GlobalDir,OutDir,"mail-whitelist");
830 DoLink(GlobalDir,OutDir,"forward-alias");
832 if ExtraList.has_key("[DNS]"):
833 GenDNS(l,OutDir+"dns-zone",Split[1]);
834 GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
836 if ExtraList.has_key("[BSMTP]"):
837 GenBSMTP(l,OutDir+"bsmtp",Split[1])
839 if ExtraList.has_key("[PRIVATE]"):
840 DoLink(GlobalDir,OutDir,"debian-private")