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,UidShift):
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" % ((int(GetAttr(x,"uidNumber"))+UidShift),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,UidShift):
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 NewGid = int(GroupIDMap[x]);
247 NewGid = NewGid + UidShift
248 Line = "%s:x:%u:" % (x,NewGid)
250 for I in GroupMap[x]:
251 Line = Line + ("%s%s" % (Comma,I));
253 Line = Sanitize(Line) + "\n";
254 F.write("0%u %s" % (J,Line));
255 F.write(".%s %s" % (x,Line));
256 F.write("=%u %s" % (NewGid,Line));
259 # Oops, something unspeakable happened.
265 # Generate the email forwarding list
266 def GenForward(l,File):
269 OldMask = os.umask(0022);
270 F = open(File + ".tmp","w",0644);
273 # Fetch all the users
275 if PasswdAttrs == None:
278 # Write out the email address for each user
279 for x in PasswdAttrs:
280 if x[1].has_key("emailForward") == 0 or IsInGroup(x) == 0:
283 # Do not allow people to try to buffer overflow busted parsers
284 if len(GetAttr(x,"emailForward")) > 200:
287 # Check the forwarding address
288 if EmailCheck.match(GetAttr(x,"emailForward")) == None:
290 Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailForward"));
291 Line = Sanitize(Line) + "\n";
294 # Oops, something unspeakable happened.
300 def GenAllForward(l,File):
303 OldMask = os.umask(0022);
304 Fdb = os.popen("cdbmake %s %s.tmp"%(File,File),"w");
307 # Fetch all the users
309 if PasswdAttrs == None:
312 # Write out the email address for each user
313 for x in PasswdAttrs:
314 if x[1].has_key("emailForward") == 0:
317 # Do not allow people to try to buffer overflow busted parsers
318 Forward = GetAttr(x,"emailForward");
319 if len(Forward) > 200:
322 # Check the forwarding address
323 if EmailCheck.match(Forward) == None:
326 User = GetAttr(x,"uid");
327 Fdb.write("+%d,%d:%s->%s\n"%(len(User),len(Forward),User,Forward));
329 # Oops, something unspeakable happened.
333 if Fdb.close() != None:
334 raise "cdbmake gave an error";
336 # Generate the anon XEarth marker file
337 def GenMarkers(l,File):
340 F = open(File + ".tmp","w");
342 # Fetch all the users
344 if PasswdAttrs == None:
347 # Write out the position for each user
348 for x in PasswdAttrs:
349 if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
352 Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
353 Line = Sanitize(Line) + "\n";
358 # Oops, something unspeakable happened.
364 # Generate the debian-private subscription list
365 def GenPrivate(l,File):
368 F = open(File + ".tmp","w");
370 # Fetch all the users
372 if PasswdAttrs == None:
375 # Write out the position for each user
376 for x in PasswdAttrs:
377 if x[1].has_key("privateSub") == 0:
380 # If the account is locked, do not write it
381 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
382 or GetAttr(x,"userPassword").startswith("!"):
385 # If the account has no PGP key, do not write it
386 if x[1].has_key("keyFingerPrint") == 0:
389 # Must be in the Debian group (yuk, hard coded for now)
390 if GetAttr(x,"gidNumber") != "800":
394 Line = "%s"%(GetAttr(x,"privateSub"));
395 Line = Sanitize(Line) + "\n";
400 # Oops, something unspeakable happened.
406 # Generate a list of locked accounts
407 def GenDisabledAccounts(l,File):
410 F = open(File + ".tmp","w");
412 # Fetch all the users
414 if PasswdAttrs == None:
418 for x in PasswdAttrs:
419 if x[1].has_key("uidNumber") == 0:
422 Pass = GetAttr(x,"userPassword");
424 # *LK* is the reference value for a locked account
425 # password starting with ! is also a locked account
426 if Pass.find("*LK*") != -1 or Pass.startswith("!"):
427 # Format is <login>:<reason>
428 Line = "%s:%s" % (GetAttr(x,"uid"), "Account is locked")
431 F.write(Sanitize(Line) + "\n")
433 # Oops, something unspeakable happened.
439 # Generate the list of local addresses that refuse all mail
440 def GenMailDisable(l,File):
443 F = open(File + ".tmp","w");
445 # Fetch all the users
447 if PasswdAttrs == None:
450 for x in PasswdAttrs:
453 # If the account is locked, disable incoming mail
454 if (GetAttr(x,"userPassword").find("*LK*") != -1):
455 if GetAttr(x,"uid") == "luther":
458 Reason = "user account locked"
460 if x[1].has_key("mailDisableMessage"):
461 Reason = GetAttr(x,"mailDisableMessage")
465 # Must be in the Debian group (yuk, hard coded for now)
466 if GetAttr(x,"gidNumber") != "800":
470 Line = "%s: %s"%(GetAttr(x,"uid"),Reason);
471 Line = Sanitize(Line) + "\n";
476 # Oops, something unspeakable happened.
482 # Generate a list of uids that should have boolean affects applied
483 def GenMailBool(l,File,Key):
486 F = open(File + ".tmp","w");
488 # Fetch all the users
490 if PasswdAttrs == None:
493 for x in PasswdAttrs:
496 if x[1].has_key(Key) == 0:
499 # Must be in the Debian group (yuk, hard coded for now)
500 if GetAttr(x,"gidNumber") != "800":
503 if GetAttr(x,Key) != "TRUE":
507 Line = "%s"%(GetAttr(x,"uid"));
508 Line = Sanitize(Line) + "\n";
513 # Oops, something unspeakable happened.
519 # Generate a list of hosts for RBL or whitelist purposes.
520 def GenMailList(l,File,Key):
523 F = open(File + ".tmp","w");
525 # Fetch all the users
527 if PasswdAttrs == None:
530 for x in PasswdAttrs:
533 if x[1].has_key(Key) == 0:
536 # Must be in the Debian group (yuk, hard coded for now)
537 if GetAttr(x,"gidNumber") != "800":
544 if Key == "mailWhitelist":
545 if re.match('^[-\w.]+(/[\d]+)?$',z) == None:
548 if re.match('^[-\w.]+$',z) == None:
552 Line = GetAttr(x,"uid")
556 if Key == "mailRHSBL":
557 Line += "/$sender_address_domain"
560 Line = Sanitize(Line) + "\n";
565 # Oops, something unspeakable happened.
571 # Generate the DNS Zone file
572 def GenDNS(l,File,HomePrefix):
575 F = open(File + ".tmp","w");
577 # Fetch all the users
579 if PasswdAttrs == None:
582 # Write out the zone file entry for each user
583 for x in PasswdAttrs:
584 if x[1].has_key("dnsZoneEntry") == 0:
587 # If the account has no PGP key, do not write it
588 if x[1].has_key("keyFingerPrint") == 0:
591 F.write("; %s\n"%(EmailAddress(x)));
592 for z in x[1]["dnsZoneEntry"]:
593 Split = z.lower().split()
594 if Split[1].lower() == 'in':
595 for y in range(0,len(Split)):
598 Line = " ".join(Split) + "\n";
601 Host = Split[0] + DNSZone;
602 if BSMTPCheck.match(Line) != None:
603 F.write("; Has BSMTP\n");
605 # Write some identification information
606 if Split[2].lower() == "a":
607 Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
608 for y in x[1]["keyFingerPrint"]:
609 Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
612 Line = "; Err %s"%(str(Split));
617 F.write("; Errors\n");
620 # Oops, something unspeakable happened.
626 # Generate the DNS SSHFP records
627 def GenSSHFP(l,File,HomePrefix):
630 F = open(File + ".tmp","w")
632 # Fetch all the hosts
634 if HostAttrs == None:
638 if x[1].has_key("hostname") == 0 or \
639 x[1].has_key("sshRSAHostKey") == 0:
641 Host = GetAttr(x,"hostname");
643 for I in x[1]["sshRSAHostKey"]:
645 if Split[0] == 'ssh-rsa':
647 if Split[0] == 'ssh-dss':
649 if Algorithm == None:
651 Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
652 Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
653 Line = Sanitize(Line) + "\n"
655 # Oops, something unspeakable happened.
661 # Generate the BSMTP file
662 def GenBSMTP(l,File,HomePrefix):
665 F = open(File + ".tmp","w");
667 # Fetch all the users
669 if PasswdAttrs == None:
672 # Write out the zone file entry for each user
673 for x in PasswdAttrs:
674 if x[1].has_key("dnsZoneEntry") == 0:
677 # If the account has no PGP key, do not write it
678 if x[1].has_key("keyFingerPrint") == 0:
681 for z in x[1]["dnsZoneEntry"]:
682 Split = z.lower().split()
683 if Split[1].lower() == 'in':
684 for y in range(0,len(Split)):
687 Line = " ".join(Split) + "\n";
689 Host = Split[0] + DNSZone;
690 if BSMTPCheck.match(Line) != None:
691 F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
692 GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
695 F.write("; Errors\n");
698 # Oops, something unspeakable happened.
704 # Generate the ssh known hosts file
705 def GenSSHKnown(l,File):
708 OldMask = os.umask(0022);
709 F = open(File + ".tmp","w",0644);
713 if HostAttrs == None:
717 if x[1].has_key("hostname") == 0 or \
718 x[1].has_key("sshRSAHostKey") == 0:
720 Host = GetAttr(x,"hostname");
721 SHost = Host.find(".")
722 for I in x[1]["sshRSAHostKey"]:
724 Line = "%s,%s %s" %(Host,socket.gethostbyname(Host),I);
726 Line = "%s,%s,%s %s" %(Host,Host[0:SHost],socket.gethostbyname(Host),I);
727 Line = Sanitize(Line) + "\n";
729 # Oops, something unspeakable happened.
735 # Generate the debianhosts file (list of all IP addresses)
736 def GenHosts(l,File):
739 OldMask = os.umask(0022);
740 F = open(File + ".tmp","w",0644);
743 # Fetch all the hosts
744 HostNames = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"hostname=*",\
747 if HostNames == None:
751 if x[1].has_key("hostname") == 0:
753 Host = GetAttr(x,"hostname");
755 Addr = socket.gethostbyname(Host);
756 F.write(Addr + "\n");
759 # Oops, something unspeakable happened.
765 # Connect to the ldap server
766 l = ldap.open(LDAPServer);
767 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
768 Pass = F.readline().strip().split(" ")
770 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
772 # Fetch all the groups
774 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
775 ["gid","gidNumber"]);
777 # Generate the GroupMap and GroupIDMap
779 if x[1].has_key("gidNumber") == 0:
781 GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
783 # Fetch all the users
784 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
785 ["uid","uidNumber","gidNumber","supplementaryGid",\
786 "gecos","loginShell","userPassword","shadowLastChange",\
787 "shadowMin","shadowMax","shadowWarning","shadowinactive",
788 "shadowexpire","emailForward","latitude","longitude",\
789 "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
790 "keyFingerPrint","privateSub","mailDisableMessage",\
791 "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
793 # Fetch all the hosts
794 HostAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
795 ["hostname","sshRSAHostKey"]);
797 # Open the control file
798 if len(sys.argv) == 1:
799 F = open(GenerateConf,"r");
801 F = open(sys.argv[1],"r")
803 # Generate global things
804 GlobalDir = GenerateDir+"/";
805 GenSSHShadow(l,GlobalDir+"ssh-rsa-shadow");
806 GenAllForward(l,GlobalDir+"mail-forward.cdb");
807 GenMarkers(l,GlobalDir+"markers");
808 GenPrivate(l,GlobalDir+"debian-private");
809 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
810 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
811 GenHosts(l,GlobalDir+"debianhosts");
812 GenMailDisable(l,GlobalDir+"mail-disable");
813 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
814 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
815 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
816 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
817 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
820 GenForward(l,GlobalDir+"forward-alias");
832 Split = Line.split(" ")
833 OutDir = GenerateDir + '/' + Split[0] + '/';
834 try: os.mkdir(OutDir);
837 # Get the group list and convert any named groups to numerics
845 if GroupIDMap.has_key(I):
846 GroupList[str(GroupIDMap[I])] = None;
851 CurrentHost = Split[0];
853 DoLink(GlobalDir,OutDir,"ssh-rsa-shadow");
854 DoLink(GlobalDir,OutDir,"debianhosts");
855 DoLink(GlobalDir,OutDir,"ssh_known_hosts");
856 DoLink(GlobalDir,OutDir,"disabled-accounts")
860 if ExtraList.has_key("[UIDSHIFT]"): UidShift=1000
861 if ExtraList.has_key("[NOPASSWD]"):
862 GenPasswd(l,OutDir+"passwd",Split[1], "*", UidShift);
864 GenPasswd(l,OutDir+"passwd",Split[1], "x", UidShift);
866 GenGroup(l,OutDir+"group", UidShift);
867 if ExtraList.has_key("[UNTRUSTED]"):
869 if not ExtraList.has_key("[NOPASSWD]"):
870 GenShadow(l,OutDir+"shadow");
872 # Link in global things
873 DoLink(GlobalDir,OutDir,"markers");
874 DoLink(GlobalDir,OutDir,"mail-forward.cdb");
875 DoLink(GlobalDir,OutDir,"mail-disable");
876 DoLink(GlobalDir,OutDir,"mail-greylist");
877 DoLink(GlobalDir,OutDir,"mail-callout");
878 DoLink(GlobalDir,OutDir,"mail-rbl");
879 DoLink(GlobalDir,OutDir,"mail-rhsbl");
880 DoLink(GlobalDir,OutDir,"mail-whitelist");
883 DoLink(GlobalDir,OutDir,"forward-alias");
885 if ExtraList.has_key("[DNS]"):
886 GenDNS(l,OutDir+"dns-zone",Split[1]);
887 GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
889 if ExtraList.has_key("[BSMTP]"):
890 GenBSMTP(l,OutDir+"bsmtp",Split[1])
892 if ExtraList.has_key("[PRIVATE]"):
893 DoLink(GlobalDir,OutDir,"debian-private")