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:
151 # If the account is locked, mark it as such in shadow
152 # See Debian Bug #308229 for why we set it to 1 instead of 0
153 if (string.find(GetAttr(x,"userPassword"),"*LK*") != -1) \
154 or GetAttr(x,"userPassword").startswith("!"):
157 ShadowExpire = GetAttr(x,"shadowexpire")
159 Line = "%s:%s:%s:%s:%s:%s:%s:%s:" % (GetAttr(x,"uid"),\
160 Pass,GetAttr(x,"shadowLastChange"),\
161 GetAttr(x,"shadowMin"),GetAttr(x,"shadowMax"),\
162 GetAttr(x,"shadowWarning"),GetAttr(x,"shadowinactive"),\
164 Line = Sanitize(Line) + "\n";
165 F.write("0%u %s" % (I,Line));
166 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
169 # Oops, something unspeakable happened.
175 # Generate the shadow list
176 def GenSSHShadow(l,File):
179 OldMask = os.umask(0077);
180 F = open(File + ".tmp","w",0600);
183 # Fetch all the users
185 if PasswdAttrs == None:
188 for x in PasswdAttrs:
189 # If the account is locked, do not write it.
190 # This is a partial stop-gap. The ssh also needs to change this
191 # to ignore ~/.ssh/authorized* files.
192 if (string.find(GetAttr(x,"userPassword"),"*LK*") != -1) \
193 or GetAttr(x,"userPassword").startswith("!"):
196 if x[1].has_key("uidNumber") == 0 or \
197 x[1].has_key("sshRSAAuthKey") == 0:
199 for I in x[1]["sshRSAAuthKey"]:
200 User = GetAttr(x,"uid");
201 Line = "%s: %s" %(User,I);
202 Line = Sanitize(Line) + "\n";
204 # Oops, something unspeakable happened.
210 # Generate the group list
211 def GenGroup(l,File):
214 F = open(File + ".tdb.tmp","w");
216 # Generate the GroupMap
218 for x in GroupIDMap.keys():
221 # Fetch all the users
223 if PasswdAttrs == None:
226 # Sort them into a list of groups having a set of users
227 for x in PasswdAttrs:
228 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
230 if x[1].has_key("supplementaryGid") == 0:
233 for I in x[1]["supplementaryGid"]:
234 if GroupMap.has_key(I):
235 GroupMap[I].append(GetAttr(x,"uid"));
237 print "Group does not exist ",I,"but",GetAttr(x,"uid"),"is in it";
239 # Output the group file.
241 for x in GroupMap.keys():
242 if GroupIDMap.has_key(x) == 0:
244 Line = "%s:x:%u:" % (x,GroupIDMap[x]);
246 for I in GroupMap[x]:
247 Line = Line + ("%s%s" % (Comma,I));
249 Line = Sanitize(Line) + "\n";
250 F.write("0%u %s" % (J,Line));
251 F.write(".%s %s" % (x,Line));
252 F.write("=%u %s" % (GroupIDMap[x],Line));
255 # Oops, something unspeakable happened.
261 # Generate the email forwarding list
262 def GenForward(l,File):
265 OldMask = os.umask(0022);
266 F = open(File + ".tmp","w",0644);
269 # Fetch all the users
271 if PasswdAttrs == None:
274 # Write out the email address for each user
275 for x in PasswdAttrs:
276 if x[1].has_key("emailForward") == 0 or IsInGroup(x) == 0:
279 # Do not allow people to try to buffer overflow busted parsers
280 if len(GetAttr(x,"emailForward")) > 200:
283 # Check the forwarding address
284 if EmailCheck.match(GetAttr(x,"emailForward")) == None:
286 Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailForward"));
287 Line = Sanitize(Line) + "\n";
290 # Oops, something unspeakable happened.
296 def GenAllForward(l,File):
299 OldMask = os.umask(0022);
300 Fdb = os.popen("cdbmake %s %s.tmp"%(File,File),"w");
303 # Fetch all the users
305 if PasswdAttrs == None:
308 # Write out the email address for each user
309 for x in PasswdAttrs:
310 if x[1].has_key("emailForward") == 0:
313 # Do not allow people to try to buffer overflow busted parsers
314 Forward = GetAttr(x,"emailForward");
315 if len(Forward) > 200:
318 # Check the forwarding address
319 if EmailCheck.match(Forward) == None:
322 User = GetAttr(x,"uid");
323 Fdb.write("+%d,%d:%s->%s\n"%(len(User),len(Forward),User,Forward));
325 # Oops, something unspeakable happened.
329 if Fdb.close() != None:
330 raise "cdbmake gave an error";
332 # Generate the anon XEarth marker file
333 def GenMarkers(l,File):
336 F = open(File + ".tmp","w");
338 # Fetch all the users
340 if PasswdAttrs == None:
343 # Write out the position for each user
344 for x in PasswdAttrs:
345 if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
348 Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
349 Line = Sanitize(Line) + "\n";
354 # Oops, something unspeakable happened.
360 # Generate the debian-private subscription list
361 def GenPrivate(l,File):
364 F = open(File + ".tmp","w");
366 # Fetch all the users
368 if PasswdAttrs == None:
371 # Write out the position for each user
372 for x in PasswdAttrs:
373 if x[1].has_key("privateSub") == 0:
376 # If the account is locked, do not write it
377 if (string.find(GetAttr(x,"userPassword"),"*LK*") != -1) \
378 or GetAttr(x,"userPassword").startswith("!"):
381 # If the account has no PGP key, do not write it
382 if x[1].has_key("keyFingerPrint") == 0:
385 # Must be in the Debian group (yuk, hard coded for now)
386 if GetAttr(x,"gidNumber") != "800":
390 Line = "%s"%(GetAttr(x,"privateSub"));
391 Line = Sanitize(Line) + "\n";
396 # Oops, something unspeakable happened.
402 # Generate a list of locked accounts
403 def GenDisabledAccounts(l,File):
406 F = open(File + ".tmp","w");
408 # Fetch all the users
410 if PasswdAttrs == None:
414 for x in PasswdAttrs:
415 if x[1].has_key("uidNumber") == 0:
418 Pass = GetAttr(x,"userPassword");
420 # *LK* is the reference value for a locked account
421 # password starting with ! is also a locked account
422 if string.find(Pass,"*LK*") != -1 or Pass.startswith("!"):
423 # Format is <login>:<reason>
424 Line = "%s:%s" % (GetAttr(x,"uid"), "Account is locked")
427 F.write(Sanitize(Line) + "\n")
429 # Oops, something unspeakable happened.
435 # Generate the list of local addresses that refuse all mail
436 def GenMailDisable(l,File):
439 F = open(File + ".tmp","w");
441 # Fetch all the users
443 if PasswdAttrs == None:
446 for x in PasswdAttrs:
449 # If the account is locked, disable incoming mail
450 if (string.find(GetAttr(x,"userPassword"),"*LK*") != -1):
451 if GetAttr(x,"uid") == "luther":
454 Reason = "user account locked"
456 if x[1].has_key("mailDisableMessage"):
457 Reason = GetAttr(x,"mailDisableMessage")
461 # Must be in the Debian group (yuk, hard coded for now)
462 if GetAttr(x,"gidNumber") != "800":
466 Line = "%s: %s"%(GetAttr(x,"uid"),Reason);
467 Line = Sanitize(Line) + "\n";
472 # Oops, something unspeakable happened.
478 # Generate a list of uids that should have boolean affects applied
479 def GenMailBool(l,File,Key):
482 F = open(File + ".tmp","w");
484 # Fetch all the users
486 if PasswdAttrs == None:
489 for x in PasswdAttrs:
492 if x[1].has_key(Key) == 0:
495 # Must be in the Debian group (yuk, hard coded for now)
496 if GetAttr(x,"gidNumber") != "800":
499 if GetAttr(x,Key) != "TRUE":
503 Line = "%s"%(GetAttr(x,"uid"));
504 Line = Sanitize(Line) + "\n";
509 # Oops, something unspeakable happened.
515 # Generate a list of hosts for RBL or whitelist purposes.
516 def GenMailList(l,File,Key):
519 F = open(File + ".tmp","w");
521 # Fetch all the users
523 if PasswdAttrs == None:
526 for x in PasswdAttrs:
529 if x[1].has_key(Key) == 0:
532 # Must be in the Debian group (yuk, hard coded for now)
533 if GetAttr(x,"gidNumber") != "800":
540 if Key == "mailWhitelist":
541 if re.match('^[-\w.]+(/[\d]+)?$',z) == None:
544 if re.match('^[-\w.]+$',z) == None:
548 Line = GetAttr(x,"uid")
552 if Key == "mailRHSBL":
553 Line += "/$sender_address_domain"
556 Line = Sanitize(Line) + "\n";
561 # Oops, something unspeakable happened.
567 # Generate the DNS Zone file
568 def GenDNS(l,File,HomePrefix):
571 F = open(File + ".tmp","w");
573 # Fetch all the users
575 if PasswdAttrs == None:
578 # Write out the zone file entry for each user
579 for x in PasswdAttrs:
580 if x[1].has_key("dnsZoneEntry") == 0:
583 # If the account has no PGP key, do not write it
584 if x[1].has_key("keyFingerPrint") == 0:
587 F.write("; %s\n"%(EmailAddress(x)));
588 for z in x[1]["dnsZoneEntry"]:
589 Split = string.split(string.lower(z));
590 if string.lower(Split[1]) == 'in':
591 for y in range(0,len(Split)):
594 Line = string.join(Split," ") + "\n";
597 Host = Split[0] + DNSZone;
598 if BSMTPCheck.match(Line) != None:
599 F.write("; Has BSMTP\n");
601 # Write some identification information
602 if string.lower(Split[2]) == "a":
603 Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
604 for y in x[1]["keyFingerPrint"]:
605 Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
608 Line = "; Err %s"%(str(Split));
613 F.write("; Errors\n");
616 # Oops, something unspeakable happened.
622 # Generate the DNS SSHFP records
623 def GenSSHFP(l,File,HomePrefix):
626 F = open(File + ".tmp","w")
628 # Fetch all the hosts
630 if HostAttrs == None:
634 if x[1].has_key("hostname") == 0 or \
635 x[1].has_key("sshRSAHostKey") == 0:
637 Host = GetAttr(x,"hostname");
639 for I in x[1]["sshRSAHostKey"]:
640 Split = string.split(I)
641 if Split[0] == 'ssh-rsa':
643 if Split[0] == 'ssh-dss':
645 if Algorithm == None:
647 Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
648 Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
649 Line = Sanitize(Line) + "\n"
651 # Oops, something unspeakable happened.
657 # Generate the BSMTP file
658 def GenBSMTP(l,File,HomePrefix):
661 F = open(File + ".tmp","w");
663 # Fetch all the users
665 if PasswdAttrs == None:
668 # Write out the zone file entry for each user
669 for x in PasswdAttrs:
670 if x[1].has_key("dnsZoneEntry") == 0:
673 # If the account has no PGP key, do not write it
674 if x[1].has_key("keyFingerPrint") == 0:
677 for z in x[1]["dnsZoneEntry"]:
678 Split = string.split(string.lower(z));
679 if string.lower(Split[1]) == 'in':
680 for y in range(0,len(Split)):
683 Line = string.join(Split," ") + "\n";
685 Host = Split[0] + DNSZone;
686 if BSMTPCheck.match(Line) != None:
687 F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
688 GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
691 F.write("; Errors\n");
694 # Oops, something unspeakable happened.
700 # Generate the ssh known hosts file
701 def GenSSHKnown(l,File):
704 OldMask = os.umask(0022);
705 F = open(File + ".tmp","w",0644);
709 if HostAttrs == None:
713 if x[1].has_key("hostname") == 0 or \
714 x[1].has_key("sshRSAHostKey") == 0:
716 Host = GetAttr(x,"hostname");
717 SHost = string.find(Host,".");
718 for I in x[1]["sshRSAHostKey"]:
720 Line = "%s,%s %s" %(Host,socket.gethostbyname(Host),I);
722 Line = "%s,%s,%s %s" %(Host,Host[0:SHost],socket.gethostbyname(Host),I);
723 Line = Sanitize(Line) + "\n";
725 # Oops, something unspeakable happened.
731 # Generate the debianhosts file (list of all IP addresses)
732 def GenHosts(l,File):
735 OldMask = os.umask(0022);
736 F = open(File + ".tmp","w",0644);
739 # Fetch all the hosts
740 HostNames = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"hostname=*",\
743 if HostNames == None:
747 if x[1].has_key("hostname") == 0:
749 Host = GetAttr(x,"hostname");
751 Addr = socket.gethostbyname(Host);
752 F.write(Addr + "\n");
755 # Oops, something unspeakable happened.
761 # Connect to the ldap server
762 l = ldap.open(LDAPServer);
763 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
764 Pass = string.split(string.strip(F.readline())," ");
766 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
768 # Fetch all the groups
770 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
771 ["gid","gidNumber"]);
773 # Generate the GroupMap and GroupIDMap
775 if x[1].has_key("gidNumber") == 0:
777 GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
779 # Fetch all the users
780 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
781 ["uid","uidNumber","gidNumber","supplementaryGid",\
782 "gecos","loginShell","userPassword","shadowLastChange",\
783 "shadowMin","shadowMax","shadowWarning","shadowinactive",
784 "shadowexpire","emailForward","latitude","longitude",\
785 "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
786 "keyFingerPrint","privateSub","mailDisableMessage",\
787 "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
789 # Fetch all the hosts
790 HostAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
791 ["hostname","sshRSAHostKey"]);
793 # Open the control file
794 if len(sys.argv) == 1:
795 F = open(GenerateConf,"r");
797 F = open(sys.argv[1],"r")
799 # Generate global things
800 GlobalDir = GenerateDir+"/";
801 GenSSHShadow(l,GlobalDir+"ssh-rsa-shadow");
802 GenAllForward(l,GlobalDir+"mail-forward.cdb");
803 GenMarkers(l,GlobalDir+"markers");
804 GenPrivate(l,GlobalDir+"debian-private");
805 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
806 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
807 GenHosts(l,GlobalDir+"debianhosts");
808 GenMailDisable(l,GlobalDir+"mail-disable");
809 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
810 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
811 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
812 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
813 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
816 GenForward(l,GlobalDir+"forward-alias");
822 Line = string.strip(Line);
828 Split = string.split(Line," ");
829 OutDir = GenerateDir + '/' + Split[0] + '/';
830 try: os.mkdir(OutDir);
833 # Get the group list and convert any named groups to numerics
841 if GroupIDMap.has_key(I):
842 GroupList[str(GroupIDMap[I])] = None;
847 CurrentHost = Split[0];
849 DoLink(GlobalDir,OutDir,"ssh-rsa-shadow");
850 DoLink(GlobalDir,OutDir,"debianhosts");
851 DoLink(GlobalDir,OutDir,"ssh_known_hosts");
852 DoLink(GlobalDir,OutDir,"disabled-accounts")
855 GenPasswd(l,OutDir+"passwd",Split[1]);
857 GenGroup(l,OutDir+"group");
858 if ExtraList.has_key("[UNTRUSTED]"):
860 if not ExtraList.has_key("[NOPASSWD]"):
861 GenShadow(l,OutDir+"shadow");
863 # Link in global things
864 DoLink(GlobalDir,OutDir,"markers");
865 DoLink(GlobalDir,OutDir,"mail-forward.cdb");
866 DoLink(GlobalDir,OutDir,"mail-disable");
867 DoLink(GlobalDir,OutDir,"mail-greylist");
868 DoLink(GlobalDir,OutDir,"mail-callout");
869 DoLink(GlobalDir,OutDir,"mail-rbl");
870 DoLink(GlobalDir,OutDir,"mail-rhsbl");
871 DoLink(GlobalDir,OutDir,"mail-whitelist");
874 DoLink(GlobalDir,OutDir,"forward-alias");
876 if ExtraList.has_key("[DNS]"):
877 GenDNS(l,OutDir+"dns-zone",Split[1]);
878 GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
880 if ExtraList.has_key("[BSMTP]"):
881 GenBSMTP(l,OutDir+"bsmtp",Split[1])
883 if ExtraList.has_key("[PRIVATE]"):
884 DoLink(GlobalDir,OutDir,"debian-private")