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, shutil
25 from userdir_ldap import *;
35 EmailCheck = re.compile("^([^ <>@]+@[^ ,<>@]+)?$");
36 BSMTPCheck = re.compile(".*mx 0 (gluck)\.debian\.org\..*",re.DOTALL);
37 DNSZone = ".debian.net"
38 Keyrings = [ "/org/keyring.debian.org/keyrings/debian-keyring.gpg",
39 "/org/keyring.debian.org/keyrings/debian-keyring.pgp" ]
42 return Str.translate(string.maketrans("\n\r\t","$$$"))
44 def DoLink(From,To,File):
45 try: posix.remove(To+File);
47 posix.link(From+File,To+File);
49 # See if this user is in the group list
50 def IsInGroup(DnRecord):
54 # See if the primary group is in the list
55 if Allowed.has_key(GetAttr(DnRecord,"gidNumber")) != 0:
58 # Check the host based ACL
59 if DnRecord[1].has_key("allowedHost") != 0:
60 for I in DnRecord[1]["allowedHost"]:
64 # See if there are supplementary groups
65 if DnRecord[1].has_key("supplementaryGid") == 0:
68 # Check the supplementary groups
69 for I in DnRecord[1]["supplementaryGid"]:
70 if Allowed.has_key(I):
79 try: os.remove(File + ".tmp");
81 try: os.remove(File + ".tdb.tmp");
87 os.rename(File + ".tmp",File);
90 os.rename(File + ".tdb.tmp",File+".tdb");
92 # Generate the password list
93 def GenPasswd(l,File,HomePrefix,PwdMarker):
96 F = open(File + ".tdb.tmp","w");
100 if PasswdAttrs == None:
104 for x in PasswdAttrs:
105 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
108 # Do not let people try to buffer overflow some busted passwd parser.
109 if len(GetAttr(x,"gecos")) > 100 or len(GetAttr(x,"loginShell")) > 50:
112 Line = "%s:%s:%s:%s:%s:%s%s:%s" % (GetAttr(x,"uid"),\
114 GetAttr(x,"uidNumber"),GetAttr(x,"gidNumber"),\
115 GetAttr(x,"gecos"),HomePrefix,GetAttr(x,"uid"),\
116 GetAttr(x,"loginShell"));
118 Line = Sanitize(Line) + "\n";
119 F.write("0%u %s" % (I,Line));
120 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
121 F.write("=%s %s" % (GetAttr(x,"uidNumber"),Line));
124 # Oops, something unspeakable happened.
130 # Generate the shadow list
131 def GenShadow(l,File):
134 OldMask = os.umask(0077);
135 F = open(File + ".tdb.tmp","w",0600);
138 # Fetch all the users
140 if PasswdAttrs == None:
144 for x in PasswdAttrs:
145 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
148 Pass = GetAttr(x,"userPassword");
149 if Pass[0:7] != "{crypt}" or len(Pass) > 50:
154 # If the account is locked, mark it as such in shadow
155 # See Debian Bug #308229 for why we set it to 1 instead of 0
156 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
157 or GetAttr(x,"userPassword").startswith("!"):
160 ShadowExpire = GetAttr(x,"shadowexpire")
162 Line = "%s:%s:%s:%s:%s:%s:%s:%s:" % (GetAttr(x,"uid"),\
163 Pass,GetAttr(x,"shadowLastChange"),\
164 GetAttr(x,"shadowMin"),GetAttr(x,"shadowMax"),\
165 GetAttr(x,"shadowWarning"),GetAttr(x,"shadowinactive"),\
167 Line = Sanitize(Line) + "\n";
168 F.write("0%u %s" % (I,Line));
169 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
172 # Oops, something unspeakable happened.
178 # Generate the shadow list
179 def GenSSHShadow(l,File):
182 OldMask = os.umask(0077);
183 F = open(File + ".tmp","w",0600);
186 # Fetch all the users
188 if PasswdAttrs == None:
191 for x in PasswdAttrs:
192 # If the account is locked, do not write it.
193 # This is a partial stop-gap. The ssh also needs to change this
194 # to ignore ~/.ssh/authorized* files.
195 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
196 or GetAttr(x,"userPassword").startswith("!"):
199 if x[1].has_key("uidNumber") == 0 or \
200 x[1].has_key("sshRSAAuthKey") == 0:
202 for I in x[1]["sshRSAAuthKey"]:
203 User = GetAttr(x,"uid");
204 Line = "%s: %s" %(User,I);
205 Line = Sanitize(Line) + "\n";
207 # Oops, something unspeakable happened.
213 # Generate the group list
214 def GenGroup(l,File):
217 F = open(File + ".tdb.tmp","w");
219 # Generate the GroupMap
221 for x in GroupIDMap.keys():
224 # Fetch all the users
226 if PasswdAttrs == None:
229 # Sort them into a list of groups having a set of users
230 for x in PasswdAttrs:
231 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
233 if x[1].has_key("supplementaryGid") == 0:
236 for I in x[1]["supplementaryGid"]:
237 if GroupMap.has_key(I):
238 GroupMap[I].append(GetAttr(x,"uid"));
240 print "Group does not exist ",I,"but",GetAttr(x,"uid"),"is in it";
242 # Output the group file.
244 for x in GroupMap.keys():
245 if GroupIDMap.has_key(x) == 0:
247 Line = "%s:x:%u:" % (x,GroupIDMap[x]);
249 for I in GroupMap[x]:
250 Line = Line + ("%s%s" % (Comma,I));
252 Line = Sanitize(Line) + "\n";
253 F.write("0%u %s" % (J,Line));
254 F.write(".%s %s" % (x,Line));
255 F.write("=%u %s" % (GroupIDMap[x],Line));
258 # Oops, something unspeakable happened.
264 # Generate the email forwarding list
265 def GenForward(l,File):
268 OldMask = os.umask(0022);
269 F = open(File + ".tmp","w",0644);
272 # Fetch all the users
274 if PasswdAttrs == None:
277 # Write out the email address for each user
278 for x in PasswdAttrs:
279 if x[1].has_key("emailForward") == 0 or IsInGroup(x) == 0:
282 # Do not allow people to try to buffer overflow busted parsers
283 if len(GetAttr(x,"emailForward")) > 200:
286 # Check the forwarding address
287 if EmailCheck.match(GetAttr(x,"emailForward")) == None:
289 Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailForward"));
290 Line = Sanitize(Line) + "\n";
293 # Oops, something unspeakable happened.
299 def GenAllForward(l,File):
302 OldMask = os.umask(0022);
303 Fdb = os.popen("cdbmake %s %s.tmp"%(File,File),"w");
306 # Fetch all the users
308 if PasswdAttrs == None:
311 # Write out the email address for each user
312 for x in PasswdAttrs:
313 if x[1].has_key("emailForward") == 0:
316 # Do not allow people to try to buffer overflow busted parsers
317 Forward = GetAttr(x,"emailForward");
318 if len(Forward) > 200:
321 # Check the forwarding address
322 if EmailCheck.match(Forward) == None:
325 User = GetAttr(x,"uid");
326 Fdb.write("+%d,%d:%s->%s\n"%(len(User),len(Forward),User,Forward));
328 # Oops, something unspeakable happened.
332 if Fdb.close() != None:
333 raise "cdbmake gave an error";
335 # Generate the anon XEarth marker file
336 def GenMarkers(l,File):
339 F = open(File + ".tmp","w");
341 # Fetch all the users
343 if PasswdAttrs == None:
346 # Write out the position for each user
347 for x in PasswdAttrs:
348 if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
351 Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
352 Line = Sanitize(Line) + "\n";
357 # Oops, something unspeakable happened.
363 # Generate the debian-private subscription list
364 def GenPrivate(l,File):
367 F = open(File + ".tmp","w");
369 # Fetch all the users
371 if PasswdAttrs == None:
374 # Write out the position for each user
375 for x in PasswdAttrs:
376 if x[1].has_key("privateSub") == 0:
379 # If the account is locked, do not write it
380 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
381 or GetAttr(x,"userPassword").startswith("!"):
384 # If the account has no PGP key, do not write it
385 if x[1].has_key("keyFingerPrint") == 0:
388 # Must be in the Debian group (yuk, hard coded for now)
389 if GetAttr(x,"gidNumber") != "800":
393 Line = "%s"%(GetAttr(x,"privateSub"));
394 Line = Sanitize(Line) + "\n";
399 # Oops, something unspeakable happened.
405 # Generate a list of locked accounts
406 def GenDisabledAccounts(l,File):
409 F = open(File + ".tmp","w");
411 # Fetch all the users
413 if PasswdAttrs == None:
417 for x in PasswdAttrs:
418 if x[1].has_key("uidNumber") == 0:
421 Pass = GetAttr(x,"userPassword");
423 # *LK* is the reference value for a locked account
424 # password starting with ! is also a locked account
425 if Pass.find("*LK*") != -1 or Pass.startswith("!"):
426 # Format is <login>:<reason>
427 Line = "%s:%s" % (GetAttr(x,"uid"), "Account is locked")
430 F.write(Sanitize(Line) + "\n")
432 # Oops, something unspeakable happened.
438 # Generate the list of local addresses that refuse all mail
439 def GenMailDisable(l,File):
442 F = open(File + ".tmp","w");
444 # Fetch all the users
446 if PasswdAttrs == None:
449 for x in PasswdAttrs:
452 # If the account is locked, disable incoming mail
453 if (GetAttr(x,"userPassword").find("*LK*") != -1):
454 if GetAttr(x,"uid") == "luther":
457 Reason = "user account locked"
459 if x[1].has_key("mailDisableMessage"):
460 Reason = GetAttr(x,"mailDisableMessage")
464 # Must be in the Debian group (yuk, hard coded for now)
465 if GetAttr(x,"gidNumber") != "800":
469 Line = "%s: %s"%(GetAttr(x,"uid"),Reason);
470 Line = Sanitize(Line) + "\n";
475 # Oops, something unspeakable happened.
481 # Generate a list of uids that should have boolean affects applied
482 def GenMailBool(l,File,Key):
485 F = open(File + ".tmp","w");
487 # Fetch all the users
489 if PasswdAttrs == None:
492 for x in PasswdAttrs:
495 if x[1].has_key(Key) == 0:
498 # Must be in the Debian group (yuk, hard coded for now)
499 if GetAttr(x,"gidNumber") != "800":
502 if GetAttr(x,Key) != "TRUE":
506 Line = "%s"%(GetAttr(x,"uid"));
507 Line = Sanitize(Line) + "\n";
512 # Oops, something unspeakable happened.
518 # Generate a list of hosts for RBL or whitelist purposes.
519 def GenMailList(l,File,Key):
522 F = open(File + ".tmp","w");
524 # Fetch all the users
526 if PasswdAttrs == None:
529 for x in PasswdAttrs:
532 if x[1].has_key(Key) == 0:
535 # Must be in the Debian group (yuk, hard coded for now)
536 if GetAttr(x,"gidNumber") != "800":
543 if Key == "mailWhitelist":
544 if re.match('^[-\w.]+(/[\d]+)?$',z) == None:
547 if re.match('^[-\w.]+$',z) == None:
551 Line = GetAttr(x,"uid")
555 if Key == "mailRHSBL":
556 Line += "/$sender_address_domain"
559 Line = Sanitize(Line) + "\n";
564 # Oops, something unspeakable happened.
570 # Generate the DNS Zone file
571 def GenDNS(l,File,HomePrefix):
574 F = open(File + ".tmp","w");
576 # Fetch all the users
578 if PasswdAttrs == None:
581 # Write out the zone file entry for each user
582 for x in PasswdAttrs:
583 if x[1].has_key("dnsZoneEntry") == 0:
586 # If the account has no PGP key, do not write it
587 if x[1].has_key("keyFingerPrint") == 0:
590 F.write("; %s\n"%(EmailAddress(x)));
591 for z in x[1]["dnsZoneEntry"]:
592 Split = z.lower().split()
593 if Split[1].lower() == 'in':
594 for y in range(0,len(Split)):
597 Line = " ".join(Split) + "\n";
600 Host = Split[0] + DNSZone;
601 if BSMTPCheck.match(Line) != None:
602 F.write("; Has BSMTP\n");
604 # Write some identification information
605 if Split[2].lower() == "a":
606 Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
607 for y in x[1]["keyFingerPrint"]:
608 Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
611 Line = "; Err %s"%(str(Split));
616 F.write("; Errors\n");
619 # Oops, something unspeakable happened.
625 # Generate the DNS SSHFP records
626 def GenSSHFP(l,File,HomePrefix):
629 F = open(File + ".tmp","w")
631 # Fetch all the hosts
633 if HostAttrs == None:
637 if x[1].has_key("hostname") == 0 or \
638 x[1].has_key("sshRSAHostKey") == 0:
640 Host = GetAttr(x,"hostname");
642 for I in x[1]["sshRSAHostKey"]:
644 if Split[0] == 'ssh-rsa':
646 if Split[0] == 'ssh-dss':
648 if Algorithm == None:
650 Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
651 Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
652 Line = Sanitize(Line) + "\n"
654 # Oops, something unspeakable happened.
660 # Generate the BSMTP file
661 def GenBSMTP(l,File,HomePrefix):
664 F = open(File + ".tmp","w");
666 # Fetch all the users
668 if PasswdAttrs == None:
671 # Write out the zone file entry for each user
672 for x in PasswdAttrs:
673 if x[1].has_key("dnsZoneEntry") == 0:
676 # If the account has no PGP key, do not write it
677 if x[1].has_key("keyFingerPrint") == 0:
680 for z in x[1]["dnsZoneEntry"]:
681 Split = z.lower().split()
682 if Split[1].lower() == 'in':
683 for y in range(0,len(Split)):
686 Line = " ".join(Split) + "\n";
688 Host = Split[0] + DNSZone;
689 if BSMTPCheck.match(Line) != None:
690 F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
691 GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
694 F.write("; Errors\n");
697 # Oops, something unspeakable happened.
703 # Generate the ssh known hosts file
704 def GenSSHKnown(l,File):
707 OldMask = os.umask(0022);
708 F = open(File + ".tmp","w",0644);
712 if HostAttrs == None:
716 if x[1].has_key("hostname") == 0 or \
717 x[1].has_key("sshRSAHostKey") == 0:
719 Host = GetAttr(x,"hostname");
720 SHost = Host.find(".")
721 for I in x[1]["sshRSAHostKey"]:
723 Line = "%s,%s %s" %(Host,socket.gethostbyname(Host),I);
725 Line = "%s,%s,%s %s" %(Host,Host[0:SHost],socket.gethostbyname(Host),I);
726 Line = Sanitize(Line) + "\n";
728 # Oops, something unspeakable happened.
734 # Generate the debianhosts file (list of all IP addresses)
735 def GenHosts(l,File):
738 OldMask = os.umask(0022);
739 F = open(File + ".tmp","w",0644);
742 # Fetch all the hosts
743 HostNames = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"hostname=*",\
746 if HostNames == None:
750 if x[1].has_key("hostname") == 0:
752 Host = GetAttr(x,"hostname");
754 Addr = socket.gethostbyname(Host);
755 F.write(Addr + "\n");
758 # Oops, something unspeakable happened.
764 def GenKeyrings(l,OutDir):
766 shutil.copy(k, OutDir)
768 # Connect to the ldap server
769 l = ldap.open(LDAPServer);
770 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
771 Pass = F.readline().strip().split(" ")
773 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
775 # Fetch all the groups
777 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
778 ["gid","gidNumber"]);
780 # Generate the GroupMap and GroupIDMap
782 if x[1].has_key("gidNumber") == 0:
784 GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
786 # Fetch all the users
787 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
788 ["uid","uidNumber","gidNumber","supplementaryGid",\
789 "gecos","loginShell","userPassword","shadowLastChange",\
790 "shadowMin","shadowMax","shadowWarning","shadowinactive",
791 "shadowexpire","emailForward","latitude","longitude",\
792 "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
793 "keyFingerPrint","privateSub","mailDisableMessage",\
794 "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
796 # Fetch all the hosts
797 HostAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
798 ["hostname","sshRSAHostKey"]);
800 # Open the control file
801 if len(sys.argv) == 1:
802 F = open(GenerateConf,"r");
804 F = open(sys.argv[1],"r")
806 # Generate global things
807 GlobalDir = GenerateDir+"/";
808 GenSSHShadow(l,GlobalDir+"ssh-rsa-shadow");
809 GenAllForward(l,GlobalDir+"mail-forward.cdb");
810 GenMarkers(l,GlobalDir+"markers");
811 GenPrivate(l,GlobalDir+"debian-private");
812 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
813 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
814 GenHosts(l,GlobalDir+"debianhosts");
815 GenMailDisable(l,GlobalDir+"mail-disable");
816 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
817 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
818 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
819 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
820 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
821 GenKeyrings(l,GlobalDir);
824 GenForward(l,GlobalDir+"forward-alias");
836 Split = Line.split(" ")
837 OutDir = GenerateDir + '/' + Split[0] + '/';
838 try: os.mkdir(OutDir);
841 # Get the group list and convert any named groups to numerics
849 if GroupIDMap.has_key(I):
850 GroupList[str(GroupIDMap[I])] = None;
855 CurrentHost = Split[0];
857 DoLink(GlobalDir,OutDir,"ssh-rsa-shadow");
858 DoLink(GlobalDir,OutDir,"debianhosts");
859 DoLink(GlobalDir,OutDir,"ssh_known_hosts");
860 DoLink(GlobalDir,OutDir,"disabled-accounts")
863 if ExtraList.has_key("[NOPASSWD]"):
864 GenPasswd(l,OutDir+"passwd",Split[1], "*");
866 GenPasswd(l,OutDir+"passwd",Split[1], "x");
868 GenGroup(l,OutDir+"group");
869 if ExtraList.has_key("[UNTRUSTED]"):
871 if not ExtraList.has_key("[NOPASSWD]"):
872 GenShadow(l,OutDir+"shadow");
874 # Link in global things
875 DoLink(GlobalDir,OutDir,"markers");
876 DoLink(GlobalDir,OutDir,"mail-forward.cdb");
877 DoLink(GlobalDir,OutDir,"mail-disable");
878 DoLink(GlobalDir,OutDir,"mail-greylist");
879 DoLink(GlobalDir,OutDir,"mail-callout");
880 DoLink(GlobalDir,OutDir,"mail-rbl");
881 DoLink(GlobalDir,OutDir,"mail-rhsbl");
882 DoLink(GlobalDir,OutDir,"mail-whitelist");
885 DoLink(GlobalDir,OutDir,"forward-alias");
887 if ExtraList.has_key("[DNS]"):
888 GenDNS(l,OutDir+"dns-zone",Split[1]);
889 GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
891 if ExtraList.has_key("[BSMTP]"):
892 GenBSMTP(l,OutDir+"bsmtp",Split[1])
894 if ExtraList.has_key("[PRIVATE]"):
895 DoLink(GlobalDir,OutDir,"debian-private")
897 if ExtraList.has_key("[KEYRING]"):
899 DoLink(GlobalDir,OutDir,os.path.basename(k))
902 try: posix.remove(OutDir+os.path.basename(k));