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 Str.translate(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,PwdMarker):
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:%s:%s:%s:%s:%s%s:%s" % (GetAttr(x,"uid"),\
112 GetAttr(x,"uidNumber"),GetAttr(x,"gidNumber"),\
113 GetAttr(x,"gecos"),HomePrefix,GetAttr(x,"uid"),\
114 GetAttr(x,"loginShell"));
116 Line = Sanitize(Line) + "\n";
117 F.write("0%u %s" % (I,Line));
118 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
119 F.write("=%s %s" % (GetAttr(x,"uidNumber"),Line));
122 # Oops, something unspeakable happened.
128 # Generate the shadow list
129 def GenShadow(l,File):
132 OldMask = os.umask(0077);
133 F = open(File + ".tdb.tmp","w",0600);
136 # Fetch all the users
138 if PasswdAttrs == None:
142 for x in PasswdAttrs:
143 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
146 Pass = GetAttr(x,"userPassword");
147 if Pass[0:7] != "{crypt}" or len(Pass) > 50:
152 # If the account is locked, mark it as such in shadow
153 # See Debian Bug #308229 for why we set it to 1 instead of 0
154 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
155 or GetAttr(x,"userPassword").startswith("!"):
158 ShadowExpire = GetAttr(x,"shadowexpire")
160 Line = "%s:%s:%s:%s:%s:%s:%s:%s:" % (GetAttr(x,"uid"),\
161 Pass,GetAttr(x,"shadowLastChange"),\
162 GetAttr(x,"shadowMin"),GetAttr(x,"shadowMax"),\
163 GetAttr(x,"shadowWarning"),GetAttr(x,"shadowinactive"),\
165 Line = Sanitize(Line) + "\n";
166 F.write("0%u %s" % (I,Line));
167 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
170 # Oops, something unspeakable happened.
176 # Generate the shadow list
177 def GenSSHShadow(l,File):
180 OldMask = os.umask(0077);
181 F = open(File + ".tmp","w",0600);
184 # Fetch all the users
186 if PasswdAttrs == None:
189 for x in PasswdAttrs:
190 # If the account is locked, do not write it.
191 # This is a partial stop-gap. The ssh also needs to change this
192 # to ignore ~/.ssh/authorized* files.
193 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
194 or GetAttr(x,"userPassword").startswith("!"):
197 if x[1].has_key("uidNumber") == 0 or \
198 x[1].has_key("sshRSAAuthKey") == 0:
200 for I in x[1]["sshRSAAuthKey"]:
201 User = GetAttr(x,"uid");
202 Line = "%s: %s" %(User,I);
203 Line = Sanitize(Line) + "\n";
205 # Oops, something unspeakable happened.
211 # Generate the group list
212 def GenGroup(l,File):
215 F = open(File + ".tdb.tmp","w");
217 # Generate the GroupMap
219 for x in GroupIDMap.keys():
222 # Fetch all the users
224 if PasswdAttrs == None:
227 # Sort them into a list of groups having a set of users
228 for x in PasswdAttrs:
229 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
231 if x[1].has_key("supplementaryGid") == 0:
234 for I in x[1]["supplementaryGid"]:
235 if GroupMap.has_key(I):
236 GroupMap[I].append(GetAttr(x,"uid"));
238 print "Group does not exist ",I,"but",GetAttr(x,"uid"),"is in it";
240 # Output the group file.
242 for x in GroupMap.keys():
243 if GroupIDMap.has_key(x) == 0:
245 Line = "%s:x:%u:" % (x,GroupIDMap[x]);
247 for I in GroupMap[x]:
248 Line = Line + ("%s%s" % (Comma,I));
250 Line = Sanitize(Line) + "\n";
251 F.write("0%u %s" % (J,Line));
252 F.write(".%s %s" % (x,Line));
253 F.write("=%u %s" % (GroupIDMap[x],Line));
256 # Oops, something unspeakable happened.
262 # Generate the email forwarding list
263 def GenForward(l,File):
266 OldMask = os.umask(0022);
267 F = open(File + ".tmp","w",0644);
270 # Fetch all the users
272 if PasswdAttrs == None:
275 # Write out the email address for each user
276 for x in PasswdAttrs:
277 if x[1].has_key("emailForward") == 0 or IsInGroup(x) == 0:
280 # Do not allow people to try to buffer overflow busted parsers
281 if len(GetAttr(x,"emailForward")) > 200:
284 # Check the forwarding address
285 if EmailCheck.match(GetAttr(x,"emailForward")) == None:
287 Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailForward"));
288 Line = Sanitize(Line) + "\n";
291 # Oops, something unspeakable happened.
297 def GenAllForward(l,File):
300 OldMask = os.umask(0022);
301 Fdb = os.popen("cdbmake %s %s.tmp"%(File,File),"w");
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:
314 # Do not allow people to try to buffer overflow busted parsers
315 Forward = GetAttr(x,"emailForward");
316 if len(Forward) > 200:
319 # Check the forwarding address
320 if EmailCheck.match(Forward) == None:
323 User = GetAttr(x,"uid");
324 Fdb.write("+%d,%d:%s->%s\n"%(len(User),len(Forward),User,Forward));
326 # Oops, something unspeakable happened.
330 if Fdb.close() != None:
331 raise "cdbmake gave an error";
333 # Generate the anon XEarth marker file
334 def GenMarkers(l,File):
337 F = open(File + ".tmp","w");
339 # Fetch all the users
341 if PasswdAttrs == None:
344 # Write out the position for each user
345 for x in PasswdAttrs:
346 if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
349 Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
350 Line = Sanitize(Line) + "\n";
355 # Oops, something unspeakable happened.
361 # Generate the debian-private subscription list
362 def GenPrivate(l,File):
365 F = open(File + ".tmp","w");
367 # Fetch all the users
369 if PasswdAttrs == None:
372 # Write out the position for each user
373 for x in PasswdAttrs:
374 if x[1].has_key("privateSub") == 0:
377 # If the account is locked, do not write it
378 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
379 or GetAttr(x,"userPassword").startswith("!"):
382 # If the account has no PGP key, do not write it
383 if x[1].has_key("keyFingerPrint") == 0:
386 # Must be in the Debian group (yuk, hard coded for now)
387 if GetAttr(x,"gidNumber") != "800":
391 Line = "%s"%(GetAttr(x,"privateSub"));
392 Line = Sanitize(Line) + "\n";
397 # Oops, something unspeakable happened.
403 # Generate a list of locked accounts
404 def GenDisabledAccounts(l,File):
407 F = open(File + ".tmp","w");
409 # Fetch all the users
411 if PasswdAttrs == None:
415 for x in PasswdAttrs:
416 if x[1].has_key("uidNumber") == 0:
419 Pass = GetAttr(x,"userPassword");
421 # *LK* is the reference value for a locked account
422 # password starting with ! is also a locked account
423 if Pass.find("*LK*") != -1 or Pass.startswith("!"):
424 # Format is <login>:<reason>
425 Line = "%s:%s" % (GetAttr(x,"uid"), "Account is locked")
428 F.write(Sanitize(Line) + "\n")
430 # Oops, something unspeakable happened.
436 # Generate the list of local addresses that refuse all mail
437 def GenMailDisable(l,File):
440 F = open(File + ".tmp","w");
442 # Fetch all the users
444 if PasswdAttrs == None:
447 for x in PasswdAttrs:
450 # If the account is locked, disable incoming mail
451 if (GetAttr(x,"userPassword").find("*LK*") != -1):
452 if GetAttr(x,"uid") == "luther":
455 Reason = "user account locked"
457 if x[1].has_key("mailDisableMessage"):
458 Reason = GetAttr(x,"mailDisableMessage")
462 # Must be in the Debian group (yuk, hard coded for now)
463 if GetAttr(x,"gidNumber") != "800":
467 Line = "%s: %s"%(GetAttr(x,"uid"),Reason);
468 Line = Sanitize(Line) + "\n";
473 # Oops, something unspeakable happened.
479 # Generate a list of uids that should have boolean affects applied
480 def GenMailBool(l,File,Key):
483 F = open(File + ".tmp","w");
485 # Fetch all the users
487 if PasswdAttrs == None:
490 for x in PasswdAttrs:
493 if x[1].has_key(Key) == 0:
496 # Must be in the Debian group (yuk, hard coded for now)
497 if GetAttr(x,"gidNumber") != "800":
500 if GetAttr(x,Key) != "TRUE":
504 Line = "%s"%(GetAttr(x,"uid"));
505 Line = Sanitize(Line) + "\n";
510 # Oops, something unspeakable happened.
516 # Generate a list of hosts for RBL or whitelist purposes.
517 def GenMailList(l,File,Key):
520 F = open(File + ".tmp","w");
522 # Fetch all the users
524 if PasswdAttrs == None:
527 for x in PasswdAttrs:
530 if x[1].has_key(Key) == 0:
533 # Must be in the Debian group (yuk, hard coded for now)
534 if GetAttr(x,"gidNumber") != "800":
541 if Key == "mailWhitelist":
542 if re.match('^[-\w.]+(/[\d]+)?$',z) == None:
545 if re.match('^[-\w.]+$',z) == None:
549 Line = GetAttr(x,"uid")
553 if Key == "mailRHSBL":
554 Line += "/$sender_address_domain"
557 Line = Sanitize(Line) + "\n";
562 # Oops, something unspeakable happened.
568 # Generate the DNS Zone file
569 def GenDNS(l,File,HomePrefix):
572 F = open(File + ".tmp","w");
574 # Fetch all the users
576 if PasswdAttrs == None:
579 # Write out the zone file entry for each user
580 for x in PasswdAttrs:
581 if x[1].has_key("dnsZoneEntry") == 0:
584 # If the account has no PGP key, do not write it
585 if x[1].has_key("keyFingerPrint") == 0:
588 F.write("; %s\n"%(EmailAddress(x)));
589 for z in x[1]["dnsZoneEntry"]:
590 Split = z.lower().split()
591 if Split[1].lower() == 'in':
592 for y in range(0,len(Split)):
595 Line = " ".join(Split) + "\n";
598 Host = Split[0] + DNSZone;
599 if BSMTPCheck.match(Line) != None:
600 F.write("; Has BSMTP\n");
602 # Write some identification information
603 if Split[2].lower() == "a":
604 Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
605 for y in x[1]["keyFingerPrint"]:
606 Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
609 Line = "; Err %s"%(str(Split));
614 F.write("; Errors\n");
617 # Oops, something unspeakable happened.
623 # Generate the DNS SSHFP records
624 def GenSSHFP(l,File,HomePrefix):
627 F = open(File + ".tmp","w")
629 # Fetch all the hosts
631 if HostAttrs == None:
635 if x[1].has_key("hostname") == 0 or \
636 x[1].has_key("sshRSAHostKey") == 0:
638 Host = GetAttr(x,"hostname");
640 for I in x[1]["sshRSAHostKey"]:
642 if Split[0] == 'ssh-rsa':
644 if Split[0] == 'ssh-dss':
646 if Algorithm == None:
648 Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
649 Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
650 Line = Sanitize(Line) + "\n"
652 # Oops, something unspeakable happened.
658 # Generate the BSMTP file
659 def GenBSMTP(l,File,HomePrefix):
662 F = open(File + ".tmp","w");
664 # Fetch all the users
666 if PasswdAttrs == None:
669 # Write out the zone file entry for each user
670 for x in PasswdAttrs:
671 if x[1].has_key("dnsZoneEntry") == 0:
674 # If the account has no PGP key, do not write it
675 if x[1].has_key("keyFingerPrint") == 0:
678 for z in x[1]["dnsZoneEntry"]:
679 Split = z.lower().split()
680 if Split[1].lower() == 'in':
681 for y in range(0,len(Split)):
684 Line = " ".join(Split) + "\n";
686 Host = Split[0] + DNSZone;
687 if BSMTPCheck.match(Line) != None:
688 F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
689 GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
692 F.write("; Errors\n");
695 # Oops, something unspeakable happened.
701 # Generate the ssh known hosts file
702 def GenSSHKnown(l,File):
705 OldMask = os.umask(0022);
706 F = open(File + ".tmp","w",0644);
710 if HostAttrs == None:
714 if x[1].has_key("hostname") == 0 or \
715 x[1].has_key("sshRSAHostKey") == 0:
717 Host = GetAttr(x,"hostname");
718 SHost = Host.find(".")
719 for I in x[1]["sshRSAHostKey"]:
721 Line = "%s,%s %s" %(Host,socket.gethostbyname(Host),I);
723 Line = "%s,%s,%s %s" %(Host,Host[0:SHost],socket.gethostbyname(Host),I);
724 Line = Sanitize(Line) + "\n";
726 # Oops, something unspeakable happened.
732 # Generate the debianhosts file (list of all IP addresses)
733 def GenHosts(l,File):
736 OldMask = os.umask(0022);
737 F = open(File + ".tmp","w",0644);
740 # Fetch all the hosts
741 HostNames = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"hostname=*",\
744 if HostNames == None:
748 if x[1].has_key("hostname") == 0:
750 Host = GetAttr(x,"hostname");
752 Addr = socket.gethostbyname(Host);
753 F.write(Addr + "\n");
756 # Oops, something unspeakable happened.
762 # Connect to the ldap server
763 l = ldap.open(LDAPServer);
764 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
765 Pass = F.readline().strip().split(" ")
767 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
769 # Fetch all the groups
771 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
772 ["gid","gidNumber"]);
774 # Generate the GroupMap and GroupIDMap
776 if x[1].has_key("gidNumber") == 0:
778 GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
780 # Fetch all the users
781 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
782 ["uid","uidNumber","gidNumber","supplementaryGid",\
783 "gecos","loginShell","userPassword","shadowLastChange",\
784 "shadowMin","shadowMax","shadowWarning","shadowinactive",
785 "shadowexpire","emailForward","latitude","longitude",\
786 "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
787 "keyFingerPrint","privateSub","mailDisableMessage",\
788 "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
790 # Fetch all the hosts
791 HostAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
792 ["hostname","sshRSAHostKey"]);
794 # Open the control file
795 if len(sys.argv) == 1:
796 F = open(GenerateConf,"r");
798 F = open(sys.argv[1],"r")
800 # Generate global things
801 GlobalDir = GenerateDir+"/";
802 GenSSHShadow(l,GlobalDir+"ssh-rsa-shadow");
803 GenAllForward(l,GlobalDir+"mail-forward.cdb");
804 GenMarkers(l,GlobalDir+"markers");
805 GenPrivate(l,GlobalDir+"debian-private");
806 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
807 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
808 GenHosts(l,GlobalDir+"debianhosts");
809 GenMailDisable(l,GlobalDir+"mail-disable");
810 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
811 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
812 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
813 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
814 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
817 GenForward(l,GlobalDir+"forward-alias");
829 Split = Line.split(" ")
830 OutDir = GenerateDir + '/' + Split[0] + '/';
831 try: os.mkdir(OutDir);
834 # Get the group list and convert any named groups to numerics
842 if GroupIDMap.has_key(I):
843 GroupList[str(GroupIDMap[I])] = None;
848 CurrentHost = Split[0];
850 DoLink(GlobalDir,OutDir,"ssh-rsa-shadow");
851 DoLink(GlobalDir,OutDir,"debianhosts");
852 DoLink(GlobalDir,OutDir,"ssh_known_hosts");
853 DoLink(GlobalDir,OutDir,"disabled-accounts")
856 if ExtraList.has_key("[NOPASSWD]"):
857 GenPasswd(l,OutDir+"passwd",Split[1], "*");
859 GenPasswd(l,OutDir+"passwd",Split[1], "x");
861 GenGroup(l,OutDir+"group");
862 if ExtraList.has_key("[UNTRUSTED]"):
864 if not ExtraList.has_key("[NOPASSWD]"):
865 GenShadow(l,OutDir+"shadow");
867 # Link in global things
868 DoLink(GlobalDir,OutDir,"markers");
869 DoLink(GlobalDir,OutDir,"mail-forward.cdb");
870 DoLink(GlobalDir,OutDir,"mail-disable");
871 DoLink(GlobalDir,OutDir,"mail-greylist");
872 DoLink(GlobalDir,OutDir,"mail-callout");
873 DoLink(GlobalDir,OutDir,"mail-rbl");
874 DoLink(GlobalDir,OutDir,"mail-rhsbl");
875 DoLink(GlobalDir,OutDir,"mail-whitelist");
878 DoLink(GlobalDir,OutDir,"forward-alias");
880 if ExtraList.has_key("[DNS]"):
881 GenDNS(l,OutDir+"dns-zone",Split[1]);
882 GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
884 if ExtraList.has_key("[BSMTP]"):
885 GenBSMTP(l,OutDir+"bsmtp",Split[1])
887 if ExtraList.has_key("[PRIVATE]"):
888 DoLink(GlobalDir,OutDir,"debian-private")