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,File):
183 OldMask = os.umask(0077);
184 F = open(File + ".tmp","w",0600);
187 # Fetch all the users
189 if PasswdAttrs == None:
192 for x in PasswdAttrs:
193 # If the account is locked, do not write it.
194 # This is a partial stop-gap. The ssh also needs to change this
195 # to ignore ~/.ssh/authorized* files.
196 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
197 or GetAttr(x,"userPassword").startswith("!"):
200 if x[1].has_key("uidNumber") == 0 or \
201 x[1].has_key("sshRSAAuthKey") == 0:
203 for I in x[1]["sshRSAAuthKey"]:
204 User = GetAttr(x,"uid");
205 Line = "%s: %s" %(User,I);
206 Line = Sanitize(Line) + "\n";
208 # Oops, something unspeakable happened.
214 # Generate the group list
215 def GenGroup(l,File):
218 F = open(File + ".tdb.tmp","w");
220 # Generate the GroupMap
222 for x in GroupIDMap.keys():
225 # Fetch all the users
227 if PasswdAttrs == None:
230 # Sort them into a list of groups having a set of users
231 for x in PasswdAttrs:
232 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
234 if x[1].has_key("supplementaryGid") == 0:
237 for I in x[1]["supplementaryGid"]:
238 if GroupMap.has_key(I):
239 GroupMap[I].append(GetAttr(x,"uid"));
241 print "Group does not exist ",I,"but",GetAttr(x,"uid"),"is in it";
243 # Output the group file.
245 for x in GroupMap.keys():
246 if GroupIDMap.has_key(x) == 0:
248 Line = "%s:x:%u:" % (x,GroupIDMap[x]);
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" % (GroupIDMap[x],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 def GenKeyrings(l,OutDir):
767 shutil.copy(k, OutDir)
769 # Connect to the ldap server
770 l = ldap.open(LDAPServer);
771 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
772 Pass = F.readline().strip().split(" ")
774 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
776 # Fetch all the groups
778 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
779 ["gid","gidNumber"]);
781 # Generate the GroupMap and GroupIDMap
783 if x[1].has_key("gidNumber") == 0:
785 GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
787 # Fetch all the users
788 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
789 ["uid","uidNumber","gidNumber","supplementaryGid",\
790 "gecos","loginShell","userPassword","shadowLastChange",\
791 "shadowMin","shadowMax","shadowWarning","shadowinactive",
792 "shadowexpire","emailForward","latitude","longitude",\
793 "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
794 "keyFingerPrint","privateSub","mailDisableMessage",\
795 "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
797 # Fetch all the hosts
798 HostAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
799 ["hostname","sshRSAHostKey"]);
801 # Open the control file
802 if len(sys.argv) == 1:
803 F = open(GenerateConf,"r");
805 F = open(sys.argv[1],"r")
807 # Generate global things
808 GlobalDir = GenerateDir+"/";
809 GenSSHShadow(l,GlobalDir+"ssh-rsa-shadow");
810 GenAllForward(l,GlobalDir+"mail-forward.cdb");
811 GenMarkers(l,GlobalDir+"markers");
812 GenPrivate(l,GlobalDir+"debian-private");
813 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
814 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
815 GenHosts(l,GlobalDir+"debianhosts");
816 GenMailDisable(l,GlobalDir+"mail-disable");
817 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
818 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
819 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
820 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
821 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
822 GenKeyrings(l,GlobalDir);
825 GenForward(l,GlobalDir+"forward-alias");
837 Split = Line.split(" ")
838 OutDir = GenerateDir + '/' + Split[0] + '/';
839 try: os.mkdir(OutDir);
842 # Get the group list and convert any named groups to numerics
850 if GroupIDMap.has_key(I):
851 GroupList[str(GroupIDMap[I])] = None;
856 CurrentHost = Split[0];
858 DoLink(GlobalDir,OutDir,"ssh-rsa-shadow");
859 DoLink(GlobalDir,OutDir,"debianhosts");
860 DoLink(GlobalDir,OutDir,"ssh_known_hosts");
861 DoLink(GlobalDir,OutDir,"disabled-accounts")
864 if ExtraList.has_key("[NOPASSWD]"):
865 GenPasswd(l,OutDir+"passwd",Split[1], "*");
867 GenPasswd(l,OutDir+"passwd",Split[1], "x");
869 GenGroup(l,OutDir+"group");
870 if ExtraList.has_key("[UNTRUSTED]"):
872 if not ExtraList.has_key("[NOPASSWD]"):
873 GenShadow(l,OutDir+"shadow");
875 # Link in global things
876 DoLink(GlobalDir,OutDir,"markers");
877 DoLink(GlobalDir,OutDir,"mail-forward.cdb");
878 DoLink(GlobalDir,OutDir,"mail-disable");
879 DoLink(GlobalDir,OutDir,"mail-greylist");
880 DoLink(GlobalDir,OutDir,"mail-callout");
881 DoLink(GlobalDir,OutDir,"mail-rbl");
882 DoLink(GlobalDir,OutDir,"mail-rhsbl");
883 DoLink(GlobalDir,OutDir,"mail-whitelist");
886 DoLink(GlobalDir,OutDir,"forward-alias");
888 if ExtraList.has_key("[DNS]"):
889 GenDNS(l,OutDir+"dns-zone",Split[1]);
890 GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
892 if ExtraList.has_key("[BSMTP]"):
893 GenBSMTP(l,OutDir+"bsmtp",Split[1])
895 if ExtraList.has_key("[PRIVATE]"):
896 DoLink(GlobalDir,OutDir,"debian-private")
898 if ExtraList.has_key("[KEYRING]"):
900 DoLink(GlobalDir,OutDir,os.path.basename(k))
903 try: posix.remove(OutDir+os.path.basename(k));