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>
9 # Copyright (c) 2008 Peter Palfrader <peter@palfrader.org>
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 2 of the License, or
14 # (at your option) any later version.
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License
22 # along with this program; if not, write to the Free Software
23 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 import string, re, time, ldap, getopt, sys, os, pwd, posix, socket, base64, sha, shutil
26 from userdir_ldap import *;
36 EmailCheck = re.compile("^([^ <>@]+@[^ ,<>@]+)?$");
37 BSMTPCheck = re.compile(".*mx 0 (gluck)\.debian\.org\..*",re.DOTALL);
38 DNSZone = ".debian.net"
39 Keyrings = [ "/org/keyring.debian.org/keyrings/debian-keyring.gpg",
40 "/org/keyring.debian.org/keyrings/debian-keyring.pgp" ]
43 return Str.translate(string.maketrans("\n\r\t","$$$"))
45 def DoLink(From,To,File):
46 try: posix.remove(To+File);
48 posix.link(From+File,To+File);
50 # See if this user is in the group list
51 def IsInGroup(DnRecord):
55 # See if the primary group is in the list
56 if Allowed.has_key(GetAttr(DnRecord,"gidNumber")) != 0:
59 # Check the host based ACL
60 if DnRecord[1].has_key("allowedHost") != 0:
61 for I in DnRecord[1]["allowedHost"]:
65 # See if there are supplementary groups
66 if DnRecord[1].has_key("supplementaryGid") == 0:
69 # Check the supplementary groups
70 for I in DnRecord[1]["supplementaryGid"]:
71 if Allowed.has_key(I):
80 try: os.remove(File + ".tmp");
82 try: os.remove(File + ".tdb.tmp");
88 os.rename(File + ".tmp",File);
91 os.rename(File + ".tdb.tmp",File+".tdb");
93 # Generate the password list
94 def GenPasswd(l,File,HomePrefix,PwdMarker):
97 F = open(File + ".tdb.tmp","w");
101 if PasswdAttrs == None:
105 for x in PasswdAttrs:
106 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
109 # Do not let people try to buffer overflow some busted passwd parser.
110 if len(GetAttr(x,"gecos")) > 100 or len(GetAttr(x,"loginShell")) > 50:
113 Line = "%s:%s:%s:%s:%s:%s%s:%s" % (GetAttr(x,"uid"),\
115 GetAttr(x,"uidNumber"),GetAttr(x,"gidNumber"),\
116 GetAttr(x,"gecos"),HomePrefix,GetAttr(x,"uid"),\
117 GetAttr(x,"loginShell"));
119 Line = Sanitize(Line) + "\n";
120 F.write("0%u %s" % (I,Line));
121 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
122 F.write("=%s %s" % (GetAttr(x,"uidNumber"),Line));
125 # Oops, something unspeakable happened.
131 # Generate the shadow list
132 def GenShadow(l,File):
135 OldMask = os.umask(0077);
136 F = open(File + ".tdb.tmp","w",0600);
139 # Fetch all the users
141 if PasswdAttrs == None:
145 for x in PasswdAttrs:
146 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
149 Pass = GetAttr(x,"userPassword");
150 if Pass[0:7] != "{crypt}" or len(Pass) > 50:
155 # If the account is locked, mark it as such in shadow
156 # See Debian Bug #308229 for why we set it to 1 instead of 0
157 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
158 or GetAttr(x,"userPassword").startswith("!"):
161 ShadowExpire = GetAttr(x,"shadowexpire")
163 Line = "%s:%s:%s:%s:%s:%s:%s:%s:" % (GetAttr(x,"uid"),\
164 Pass,GetAttr(x,"shadowLastChange"),\
165 GetAttr(x,"shadowMin"),GetAttr(x,"shadowMax"),\
166 GetAttr(x,"shadowWarning"),GetAttr(x,"shadowinactive"),\
168 Line = Sanitize(Line) + "\n";
169 F.write("0%u %s" % (I,Line));
170 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
173 # Oops, something unspeakable happened.
179 # Generate the shadow list
180 def GenSSHShadow(l,masterFileName):
181 # Fetch all the users
183 # Depending on config, we write out either a single file,
184 # multiple files, or both
187 OldMask = os.umask(0077);
188 masterFile = open(masterFileName + ".tmp","w",0600);
191 Die(masterFileName,masterFile,None)
195 if PasswdAttrs == None:
198 for x in PasswdAttrs:
199 # If the account is locked, do not write it.
200 # This is a partial stop-gap. The ssh also needs to change this
201 # to ignore ~/.ssh/authorized* files.
202 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
203 or GetAttr(x,"userPassword").startswith("!"):
206 if x[1].has_key("uidNumber") == 0 or \
207 x[1].has_key("sshRSAAuthKey") == 0:
209 User = GetAttr(x,"uid");
214 OldMask = os.umask(0077);
215 File = masterFileName + "-" + User
216 F = open(File + ".tmp","w",0600);
219 for I in x[1]["sshRSAAuthKey"]:
221 MultipleLine = "%s" % I
222 MultipleLine = Sanitize(MultipleLine) + "\n"
223 F.write(MultipleLine)
225 SingleLine = "%s: %s" % (User, I)
226 SingleLine = Sanitize(SingleLine) + "\n"
227 masterFile.write(SingleLine)
231 files.append(os.path.basename(File))
233 # Oops, something unspeakable happened.
236 Die(masterFileName,masterFile,None)
240 Done(masterFileName,masterFile,None)
241 files.append(os.path.basename(masterFileName))
245 # Generate the group list
246 def GenGroup(l,File):
249 F = open(File + ".tdb.tmp","w");
251 # Generate the GroupMap
253 for x in GroupIDMap.keys():
256 # Fetch all the users
258 if PasswdAttrs == None:
261 # Sort them into a list of groups having a set of users
262 for x in PasswdAttrs:
263 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
265 if x[1].has_key("supplementaryGid") == 0:
268 for I in x[1]["supplementaryGid"]:
269 if GroupMap.has_key(I):
270 GroupMap[I].append(GetAttr(x,"uid"));
272 print "Group does not exist ",I,"but",GetAttr(x,"uid"),"is in it";
274 # Output the group file.
276 for x in GroupMap.keys():
277 if GroupIDMap.has_key(x) == 0:
279 Line = "%s:x:%u:" % (x,GroupIDMap[x]);
281 for I in GroupMap[x]:
282 Line = Line + ("%s%s" % (Comma,I));
284 Line = Sanitize(Line) + "\n";
285 F.write("0%u %s" % (J,Line));
286 F.write(".%s %s" % (x,Line));
287 F.write("=%u %s" % (GroupIDMap[x],Line));
290 # Oops, something unspeakable happened.
296 # Generate the email forwarding list
297 def GenForward(l,File):
300 OldMask = os.umask(0022);
301 F = open(File + ".tmp","w",0644);
304 # Fetch all the users
306 if PasswdAttrs == None:
309 # Write out the email address for each user
310 for x in PasswdAttrs:
311 if x[1].has_key("emailForward") == 0 or IsInGroup(x) == 0:
314 # Do not allow people to try to buffer overflow busted parsers
315 if len(GetAttr(x,"emailForward")) > 200:
318 # Check the forwarding address
319 if EmailCheck.match(GetAttr(x,"emailForward")) == None:
321 Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailForward"));
322 Line = Sanitize(Line) + "\n";
325 # Oops, something unspeakable happened.
331 def GenAllForward(l,File):
334 OldMask = os.umask(0022);
335 Fdb = os.popen("cdbmake %s %s.tmp"%(File,File),"w");
338 # Fetch all the users
340 if PasswdAttrs == None:
343 # Write out the email address for each user
344 for x in PasswdAttrs:
345 if x[1].has_key("emailForward") == 0:
348 # Do not allow people to try to buffer overflow busted parsers
349 Forward = GetAttr(x,"emailForward");
350 if len(Forward) > 200:
353 # Check the forwarding address
354 if EmailCheck.match(Forward) == None:
357 User = GetAttr(x,"uid");
358 Fdb.write("+%d,%d:%s->%s\n"%(len(User),len(Forward),User,Forward));
360 # Oops, something unspeakable happened.
364 if Fdb.close() != None:
365 raise "cdbmake gave an error";
367 # Generate the anon XEarth marker file
368 def GenMarkers(l,File):
371 F = open(File + ".tmp","w");
373 # Fetch all the users
375 if PasswdAttrs == None:
378 # Write out the position for each user
379 for x in PasswdAttrs:
380 if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
383 Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
384 Line = Sanitize(Line) + "\n";
389 # Oops, something unspeakable happened.
395 # Generate the debian-private subscription list
396 def GenPrivate(l,File):
399 F = open(File + ".tmp","w");
401 # Fetch all the users
403 if PasswdAttrs == None:
406 # Write out the position for each user
407 for x in PasswdAttrs:
408 if x[1].has_key("privateSub") == 0:
411 # If the account is locked, do not write it
412 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
413 or GetAttr(x,"userPassword").startswith("!"):
416 # If the account has no PGP key, do not write it
417 if x[1].has_key("keyFingerPrint") == 0:
420 # Must be in the Debian group (yuk, hard coded for now)
421 if GetAttr(x,"gidNumber") != "800":
425 Line = "%s"%(GetAttr(x,"privateSub"));
426 Line = Sanitize(Line) + "\n";
431 # Oops, something unspeakable happened.
437 # Generate a list of locked accounts
438 def GenDisabledAccounts(l,File):
441 F = open(File + ".tmp","w");
443 # Fetch all the users
445 if PasswdAttrs == None:
449 for x in PasswdAttrs:
450 if x[1].has_key("uidNumber") == 0:
453 Pass = GetAttr(x,"userPassword");
455 # *LK* is the reference value for a locked account
456 # password starting with ! is also a locked account
457 if Pass.find("*LK*") != -1 or Pass.startswith("!"):
458 # Format is <login>:<reason>
459 Line = "%s:%s" % (GetAttr(x,"uid"), "Account is locked")
462 F.write(Sanitize(Line) + "\n")
464 # Oops, something unspeakable happened.
470 # Generate the list of local addresses that refuse all mail
471 def GenMailDisable(l,File):
474 F = open(File + ".tmp","w");
476 # Fetch all the users
478 if PasswdAttrs == None:
481 for x in PasswdAttrs:
484 # If the account is locked, disable incoming mail
485 if (GetAttr(x,"userPassword").find("*LK*") != -1):
486 if GetAttr(x,"uid") == "luther":
489 Reason = "user account locked"
491 if x[1].has_key("mailDisableMessage"):
492 Reason = GetAttr(x,"mailDisableMessage")
496 # Must be in the Debian group (yuk, hard coded for now)
497 if GetAttr(x,"gidNumber") != "800":
501 Line = "%s: %s"%(GetAttr(x,"uid"),Reason);
502 Line = Sanitize(Line) + "\n";
507 # Oops, something unspeakable happened.
513 # Generate a list of uids that should have boolean affects applied
514 def GenMailBool(l,File,Key):
517 F = open(File + ".tmp","w");
519 # Fetch all the users
521 if PasswdAttrs == None:
524 for x in PasswdAttrs:
527 if x[1].has_key(Key) == 0:
530 # Must be in the Debian group (yuk, hard coded for now)
531 if GetAttr(x,"gidNumber") != "800":
534 if GetAttr(x,Key) != "TRUE":
538 Line = "%s"%(GetAttr(x,"uid"));
539 Line = Sanitize(Line) + "\n";
544 # Oops, something unspeakable happened.
550 # Generate a list of hosts for RBL or whitelist purposes.
551 def GenMailList(l,File,Key):
554 F = open(File + ".tmp","w");
556 # Fetch all the users
558 if PasswdAttrs == None:
561 for x in PasswdAttrs:
564 if x[1].has_key(Key) == 0:
567 # Must be in the Debian group (yuk, hard coded for now)
568 if GetAttr(x,"gidNumber") != "800":
575 if Key == "mailWhitelist":
576 if re.match('^[-\w.]+(/[\d]+)?$',z) == None:
579 if re.match('^[-\w.]+$',z) == None:
583 Line = GetAttr(x,"uid")
587 if Key == "mailRHSBL":
588 Line += "/$sender_address_domain"
591 Line = Sanitize(Line) + "\n";
596 # Oops, something unspeakable happened.
602 # Generate the DNS Zone file
603 def GenDNS(l,File,HomePrefix):
606 F = open(File + ".tmp","w");
608 # Fetch all the users
610 if PasswdAttrs == None:
613 # Write out the zone file entry for each user
614 for x in PasswdAttrs:
615 if x[1].has_key("dnsZoneEntry") == 0:
618 # If the account has no PGP key, do not write it
619 if x[1].has_key("keyFingerPrint") == 0:
622 F.write("; %s\n"%(EmailAddress(x)));
623 for z in x[1]["dnsZoneEntry"]:
624 Split = z.lower().split()
625 if Split[1].lower() == 'in':
626 for y in range(0,len(Split)):
629 Line = " ".join(Split) + "\n";
632 Host = Split[0] + DNSZone;
633 if BSMTPCheck.match(Line) != None:
634 F.write("; Has BSMTP\n");
636 # Write some identification information
637 if Split[2].lower() == "a":
638 Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
639 for y in x[1]["keyFingerPrint"]:
640 Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
643 Line = "; Err %s"%(str(Split));
648 F.write("; Errors\n");
651 # Oops, something unspeakable happened.
657 # Generate the DNS SSHFP records
658 def GenSSHFP(l,File,HomePrefix):
661 F = open(File + ".tmp","w")
663 # Fetch all the hosts
665 if HostAttrs == None:
669 if x[1].has_key("hostname") == 0 or \
670 x[1].has_key("sshRSAHostKey") == 0:
672 Host = GetAttr(x,"hostname");
674 for I in x[1]["sshRSAHostKey"]:
676 if Split[0] == 'ssh-rsa':
678 if Split[0] == 'ssh-dss':
680 if Algorithm == None:
682 Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
683 Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
684 Line = Sanitize(Line) + "\n"
686 # Oops, something unspeakable happened.
692 # Generate the BSMTP file
693 def GenBSMTP(l,File,HomePrefix):
696 F = open(File + ".tmp","w");
698 # Fetch all the users
700 if PasswdAttrs == None:
703 # Write out the zone file entry for each user
704 for x in PasswdAttrs:
705 if x[1].has_key("dnsZoneEntry") == 0:
708 # If the account has no PGP key, do not write it
709 if x[1].has_key("keyFingerPrint") == 0:
712 for z in x[1]["dnsZoneEntry"]:
713 Split = z.lower().split()
714 if Split[1].lower() == 'in':
715 for y in range(0,len(Split)):
718 Line = " ".join(Split) + "\n";
720 Host = Split[0] + DNSZone;
721 if BSMTPCheck.match(Line) != None:
722 F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
723 GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
726 F.write("; Errors\n");
729 # Oops, something unspeakable happened.
735 # Generate the ssh known hosts file
736 def GenSSHKnown(l,File):
739 OldMask = os.umask(0022);
740 F = open(File + ".tmp","w",0644);
744 if HostAttrs == None:
748 if x[1].has_key("hostname") == 0 or \
749 x[1].has_key("sshRSAHostKey") == 0:
751 Host = GetAttr(x,"hostname");
753 SHost = Host.find(".")
754 if SHost != None: HostNames += [Host[0:SHost]]
758 # get IP adresses back as "proto adress" to distinguish between v4 and v6
760 IPAdressesT = set([ (a[0],a[4][0]) for a in socket.getaddrinfo(Host, None)])
762 if code[0] != -2: raise
763 for addr in IPAdressesT:
764 if addr[0] == socket.AF_INET: IPAdresses += [addr[1], "::ffff:"+addr[1]]
765 else: IPAdresses += [addr[1]]
767 for I in x[1]["sshRSAHostKey"]:
768 Line = "%s %s" %(",".join(HostNames + IPAdresses), I);
769 Line = Sanitize(Line) + "\n";
771 # Oops, something unspeakable happened.
777 # Generate the debianhosts file (list of all IP addresses)
778 def GenHosts(l,File):
781 OldMask = os.umask(0022);
782 F = open(File + ".tmp","w",0644);
785 # Fetch all the hosts
786 HostNames = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"hostname=*",\
789 if HostNames == None:
793 if x[1].has_key("hostname") == 0:
795 Host = GetAttr(x,"hostname");
797 Addr = socket.gethostbyname(Host);
798 F.write(Addr + "\n");
801 # Oops, something unspeakable happened.
807 def GenKeyrings(l,OutDir):
809 shutil.copy(k, OutDir)
811 # Connect to the ldap server
812 l = ldap.open(LDAPServer);
813 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
814 Pass = F.readline().strip().split(" ")
816 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
818 # Fetch all the groups
820 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
821 ["gid","gidNumber"]);
823 # Generate the GroupMap and GroupIDMap
825 if x[1].has_key("gidNumber") == 0:
827 GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
829 # Fetch all the users
830 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
831 ["uid","uidNumber","gidNumber","supplementaryGid",\
832 "gecos","loginShell","userPassword","shadowLastChange",\
833 "shadowMin","shadowMax","shadowWarning","shadowinactive",
834 "shadowexpire","emailForward","latitude","longitude",\
835 "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
836 "keyFingerPrint","privateSub","mailDisableMessage",\
837 "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
839 # Fetch all the hosts
840 HostAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
841 ["hostname","sshRSAHostKey"]);
843 # Open the control file
844 if len(sys.argv) == 1:
845 F = open(GenerateConf,"r");
847 F = open(sys.argv[1],"r")
849 # Generate global things
850 GlobalDir = GenerateDir+"/";
851 SSHFiles = GenSSHShadow(l,GlobalDir+"ssh-rsa-shadow");
852 GenAllForward(l,GlobalDir+"mail-forward.cdb");
853 GenMarkers(l,GlobalDir+"markers");
854 GenPrivate(l,GlobalDir+"debian-private");
855 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
856 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
857 GenHosts(l,GlobalDir+"debianhosts");
858 GenMailDisable(l,GlobalDir+"mail-disable");
859 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
860 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
861 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
862 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
863 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
864 GenKeyrings(l,GlobalDir);
867 GenForward(l,GlobalDir+"forward-alias");
879 Split = Line.split(" ")
880 OutDir = GenerateDir + '/' + Split[0] + '/';
881 try: os.mkdir(OutDir);
884 # Get the group list and convert any named groups to numerics
892 if GroupIDMap.has_key(I):
893 GroupList[str(GroupIDMap[I])] = None;
898 CurrentHost = Split[0];
900 for file in SSHFiles:
901 DoLink(GlobalDir,OutDir,file);
902 DoLink(GlobalDir,OutDir,"debianhosts");
903 DoLink(GlobalDir,OutDir,"ssh_known_hosts");
904 DoLink(GlobalDir,OutDir,"disabled-accounts")
907 if ExtraList.has_key("[NOPASSWD]"):
908 GenPasswd(l,OutDir+"passwd",Split[1], "*");
910 GenPasswd(l,OutDir+"passwd",Split[1], "x");
912 GenGroup(l,OutDir+"group");
913 if ExtraList.has_key("[UNTRUSTED]"):
915 if not ExtraList.has_key("[NOPASSWD]"):
916 GenShadow(l,OutDir+"shadow");
918 # Link in global things
919 DoLink(GlobalDir,OutDir,"markers");
920 DoLink(GlobalDir,OutDir,"mail-forward.cdb");
921 DoLink(GlobalDir,OutDir,"mail-disable");
922 DoLink(GlobalDir,OutDir,"mail-greylist");
923 DoLink(GlobalDir,OutDir,"mail-callout");
924 DoLink(GlobalDir,OutDir,"mail-rbl");
925 DoLink(GlobalDir,OutDir,"mail-rhsbl");
926 DoLink(GlobalDir,OutDir,"mail-whitelist");
929 DoLink(GlobalDir,OutDir,"forward-alias");
931 if ExtraList.has_key("[DNS]"):
932 GenDNS(l,OutDir+"dns-zone",Split[1]);
933 GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
935 if ExtraList.has_key("[BSMTP]"):
936 GenBSMTP(l,OutDir+"bsmtp",Split[1])
938 if ExtraList.has_key("[PRIVATE]"):
939 DoLink(GlobalDir,OutDir,"debian-private")
941 if ExtraList.has_key("[KEYRING]"):
943 DoLink(GlobalDir,OutDir,os.path.basename(k))
946 try: posix.remove(OutDir+os.path.basename(k));