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 Joey Schulze <joey@infodrom.org>
8 # Copyright (c) 2001-2006 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:
150 Line = "%s:%s:%s:%s:%s:%s:%s:%s:" % (GetAttr(x,"uid"),\
151 Pass,GetAttr(x,"shadowLastChange"),\
152 GetAttr(x,"shadowMin"),GetAttr(x,"shadowMax"),\
153 GetAttr(x,"shadowWarning"),GetAttr(x,"shadowinactive"),\
154 GetAttr(x,"shadowexpire"));
155 Line = Sanitize(Line) + "\n";
156 F.write("0%u %s" % (I,Line));
157 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
160 # Oops, something unspeakable happened.
166 # Generate the shadow list
167 def GenSSHShadow(l,File):
170 OldMask = os.umask(0077);
171 F = open(File + ".tmp","w",0600);
174 # Fetch all the users
176 if PasswdAttrs == None:
179 for x in PasswdAttrs:
180 # If the account is locked, do not write it.
181 # This is a partial stop-gap. The ssh also needs to change this
182 # to ignore ~/.ssh/authorized* files.
183 if (string.find(GetAttr(x,"userPassword"),"*LK*") != -1):
186 if x[1].has_key("uidNumber") == 0 or \
187 x[1].has_key("sshRSAAuthKey") == 0:
189 for I in x[1]["sshRSAAuthKey"]:
190 User = GetAttr(x,"uid");
191 Line = "%s: %s" %(User,I);
192 Line = Sanitize(Line) + "\n";
194 # Oops, something unspeakable happened.
200 # Generate the group list
201 def GenGroup(l,File):
204 F = open(File + ".tdb.tmp","w");
206 # Generate the GroupMap
208 for x in GroupIDMap.keys():
211 # Fetch all the users
213 if PasswdAttrs == None:
216 # Sort them into a list of groups having a set of users
217 for x in PasswdAttrs:
218 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
220 if x[1].has_key("supplementaryGid") == 0:
223 for I in x[1]["supplementaryGid"]:
224 if GroupMap.has_key(I):
225 GroupMap[I].append(GetAttr(x,"uid"));
227 print "Group does not exist ",I,"but",GetAttr(x,"uid"),"is in it";
229 # Output the group file.
231 for x in GroupMap.keys():
232 if GroupIDMap.has_key(x) == 0:
234 Line = "%s:x:%u:" % (x,GroupIDMap[x]);
236 for I in GroupMap[x]:
237 Line = Line + ("%s%s" % (Comma,I));
239 Line = Sanitize(Line) + "\n";
240 F.write("0%u %s" % (J,Line));
241 F.write(".%s %s" % (x,Line));
242 F.write("=%u %s" % (GroupIDMap[x],Line));
245 # Oops, something unspeakable happened.
251 # Generate the email forwarding list
252 def GenForward(l,File):
255 OldMask = os.umask(0022);
256 F = open(File + ".tmp","w",0644);
259 # Fetch all the users
261 if PasswdAttrs == None:
264 # Write out the email address for each user
265 for x in PasswdAttrs:
266 if x[1].has_key("emailForward") == 0 or IsInGroup(x) == 0:
269 # Do not allow people to try to buffer overflow busted parsers
270 if len(GetAttr(x,"emailForward")) > 200:
273 # Check the forwarding address
274 if EmailCheck.match(GetAttr(x,"emailForward")) == None:
276 Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailForward"));
277 Line = Sanitize(Line) + "\n";
280 # Oops, something unspeakable happened.
286 def GenAllForward(l,File):
289 OldMask = os.umask(0022);
290 Fdb = os.popen("cdbmake %s %s.tmp"%(File,File),"w");
293 # Fetch all the users
295 if PasswdAttrs == None:
298 # Write out the email address for each user
299 for x in PasswdAttrs:
300 if x[1].has_key("emailForward") == 0:
303 # Do not allow people to try to buffer overflow busted parsers
304 Forward = GetAttr(x,"emailForward");
305 if len(Forward) > 200:
308 # Check the forwarding address
309 if EmailCheck.match(Forward) == None:
312 User = GetAttr(x,"uid");
313 Fdb.write("+%d,%d:%s->%s\n"%(len(User),len(Forward),User,Forward));
315 # Oops, something unspeakable happened.
319 if Fdb.close() != None:
320 raise "cdbmake gave an error";
322 # Generate the anon XEarth marker file
323 def GenMarkers(l,File):
326 F = open(File + ".tmp","w");
328 # Fetch all the users
330 if PasswdAttrs == None:
333 # Write out the position for each user
334 for x in PasswdAttrs:
335 if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
338 Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
339 Line = Sanitize(Line) + "\n";
344 # Oops, something unspeakable happened.
350 # Generate the debian-private subscription list
351 def GenPrivate(l,File):
354 F = open(File + ".tmp","w");
356 # Fetch all the users
358 if PasswdAttrs == None:
361 # Write out the position for each user
362 for x in PasswdAttrs:
363 if x[1].has_key("privateSub") == 0:
366 # If the account is locked, do not write it
367 if (string.find(GetAttr(x,"userPassword"),"*LK*") != -1):
370 # If the account has no PGP key, do not write it
371 if x[1].has_key("keyFingerPrint") == 0:
374 # Must be in the Debian group (yuk, hard coded for now)
375 if GetAttr(x,"gidNumber") != "800":
379 Line = "%s"%(GetAttr(x,"privateSub"));
380 Line = Sanitize(Line) + "\n";
385 # Oops, something unspeakable happened.
391 # Generate the list of local addresses that refuse all mail
392 def GenMailDisable(l,File):
395 F = open(File + ".tmp","w");
397 # Fetch all the users
399 if PasswdAttrs == None:
402 for x in PasswdAttrs:
405 # If the account is locked, disable incoming mail
406 if (string.find(GetAttr(x,"userPassword"),"*LK*") != -1) or \
407 x[1].has_key("keyFingerPrint") == 0:
408 Reason = "user account locked"
410 if x[1].has_key("mailDisableMessage"):
411 Reason = GetAttr(x,"mailDisableMessage")
415 # Must be in the Debian group (yuk, hard coded for now)
416 if GetAttr(x,"gidNumber") != "800":
420 Line = "%s: %s"%(GetAttr(x,"uid"),Reason);
421 Line = Sanitize(Line) + "\n";
426 # Oops, something unspeakable happened.
432 # Generate a list of uids that should have boolean affects applied
433 def GenMailBool(l,File,Key):
436 F = open(File + ".tmp","w");
438 # Fetch all the users
440 if PasswdAttrs == None:
443 for x in PasswdAttrs:
446 if x[1].has_key(Key) == 0:
449 # Must be in the Debian group (yuk, hard coded for now)
450 if GetAttr(x,"gidNumber") != "800":
453 if GetAttr(x,Key) != "TRUE":
457 Line = "%s"%(GetAttr(x,"uid"));
458 Line = Sanitize(Line) + "\n";
463 # Oops, something unspeakable happened.
469 # Generate a list of hosts for RBL or whitelist purposes.
470 def GenMailList(l,File,Key):
473 F = open(File + ".tmp","w");
475 # Fetch all the users
477 if PasswdAttrs == None:
480 for x in PasswdAttrs:
483 if x[1].has_key(Key) == 0:
486 # Must be in the Debian group (yuk, hard coded for now)
487 if GetAttr(x,"gidNumber") != "800":
494 if Key == "mailWhitelist":
495 if re.match('^[-\w.]+(/[\d]+)?$',z) == None:
498 if re.match('^[-\w.]+$',z) == None:
502 Line = GetAttr(x,"uid")
506 Line = Sanitize(Line) + "\n";
511 # Oops, something unspeakable happened.
517 # Generate the DNS Zone file
518 def GenDNS(l,File,HomePrefix):
521 F = open(File + ".tmp","w");
523 # Fetch all the users
525 if PasswdAttrs == None:
528 # Write out the zone file entry for each user
529 for x in PasswdAttrs:
530 if x[1].has_key("dnsZoneEntry") == 0:
533 # If the account has no PGP key, do not write it
534 if x[1].has_key("keyFingerPrint") == 0:
537 F.write("; %s\n"%(EmailAddress(x)));
538 for z in x[1]["dnsZoneEntry"]:
539 Split = string.split(string.lower(z));
540 if string.lower(Split[1]) == 'in':
541 for y in range(0,len(Split)):
544 Line = string.join(Split," ") + "\n";
547 Host = Split[0] + DNSZone;
548 if BSMTPCheck.match(Line) != None:
549 F.write("; Has BSMTP\n");
551 # Write some identification information
552 if string.lower(Split[2]) == "a":
553 Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
554 for y in x[1]["keyFingerPrint"]:
555 Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
558 Line = "; Err %s"%(str(Split));
563 F.write("; Errors\n");
566 # Oops, something unspeakable happened.
572 # Generate the DNS SSHFP records
573 def GenSSHFP(l,File,HomePrefix):
576 F = open(File + ".tmp","w")
578 # Fetch all the hosts
580 if HostAttrs == None:
584 if x[1].has_key("hostname") == 0 or \
585 x[1].has_key("sshRSAHostKey") == 0:
587 Host = GetAttr(x,"hostname");
589 for I in x[1]["sshRSAHostKey"]:
590 Split = string.split(I)
591 if Split[0] == 'ssh-rsa':
593 if Split[0] == 'ssh-dss':
595 if Algorithm == None:
597 Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
598 Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
599 Line = Sanitize(Line) + "\n"
601 # Oops, something unspeakable happened.
607 # Generate the BSMTP file
608 def GenBSMTP(l,File,HomePrefix):
611 F = open(File + ".tmp","w");
613 # Fetch all the users
615 if PasswdAttrs == None:
618 # Write out the zone file entry for each user
619 for x in PasswdAttrs:
620 if x[1].has_key("dnsZoneEntry") == 0:
623 # If the account has no PGP key, do not write it
624 if x[1].has_key("keyFingerPrint") == 0:
627 for z in x[1]["dnsZoneEntry"]:
628 Split = string.split(string.lower(z));
629 if string.lower(Split[1]) == 'in':
630 for y in range(0,len(Split)):
633 Line = string.join(Split," ") + "\n";
635 Host = Split[0] + DNSZone;
636 if BSMTPCheck.match(Line) != None:
637 F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
638 GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
641 F.write("; Errors\n");
644 # Oops, something unspeakable happened.
650 # Generate the ssh known hosts file
651 def GenSSHKnown(l,File):
654 OldMask = os.umask(0022);
655 F = open(File + ".tmp","w",0644);
659 if HostAttrs == None:
663 if x[1].has_key("hostname") == 0 or \
664 x[1].has_key("sshRSAHostKey") == 0:
666 Host = GetAttr(x,"hostname");
667 SHost = string.find(Host,".");
668 for I in x[1]["sshRSAHostKey"]:
670 Line = "%s,%s %s" %(Host,socket.gethostbyname(Host),I);
672 Line = "%s,%s,%s %s" %(Host,Host[0:SHost],socket.gethostbyname(Host),I);
673 Line = Sanitize(Line) + "\n";
675 # Oops, something unspeakable happened.
681 # Generate the debianhosts file (list of all IP addresses)
682 def GenHosts(l,File):
685 OldMask = os.umask(0022);
686 F = open(File + ".tmp","w",0644);
689 # Fetch all the hosts
690 HostNames = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"hostname=*",\
693 if HostNames == None:
697 if x[1].has_key("hostname") == 0:
699 Host = GetAttr(x,"hostname");
701 Addr = socket.gethostbyname(Host);
702 F.write(Addr + "\n");
705 # Oops, something unspeakable happened.
711 # Connect to the ldap server
712 l = ldap.open(LDAPServer);
713 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
714 Pass = string.split(string.strip(F.readline())," ");
716 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
718 # Fetch all the groups
720 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
721 ["gid","gidNumber"]);
723 # Generate the GroupMap and GroupIDMap
725 if x[1].has_key("gidNumber") == 0:
727 GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
729 # Fetch all the users
730 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
731 ["uid","uidNumber","gidNumber","supplementaryGid",\
732 "gecos","loginShell","userPassword","shadowLastChange",\
733 "shadowMin","shadowMax","shadowWarning","shadowinactive",
734 "shadowexpire","emailForward","latitude","longitude",\
735 "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
736 "keyFingerPrint","privateSub","mailDisableMessage",\
737 "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
739 # Fetch all the hosts
740 HostAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
741 ["hostname","sshRSAHostKey"]);
743 # Open the control file
744 if len(sys.argv) == 1:
745 F = open(GenerateConf,"r");
747 F = open(sys.argv[1],"r")
749 # Generate global things
750 GlobalDir = GenerateDir+"/";
751 GenSSHShadow(l,GlobalDir+"ssh-rsa-shadow");
752 GenAllForward(l,GlobalDir+"mail-forward.cdb");
753 GenMarkers(l,GlobalDir+"markers");
754 GenPrivate(l,GlobalDir+"debian-private");
755 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
756 GenHosts(l,GlobalDir+"debianhosts");
757 GenMailDisable(l,GlobalDir+"mail-disable");
758 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
759 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
760 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
761 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
762 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
765 GenForward(l,GlobalDir+"forward-alias");
771 Line = string.strip(Line);
777 Split = string.split(Line," ");
778 OutDir = GenerateDir + '/' + Split[0] + '/';
779 try: os.mkdir(OutDir);
782 # Get the group list and convert any named groups to numerics
790 if GroupIDMap.has_key(I):
791 GroupList[str(GroupIDMap[I])] = None;
796 CurrentHost = Split[0];
799 GenPasswd(l,OutDir+"passwd",Split[1]);
801 GenGroup(l,OutDir+"group");
802 if ExtraList.has_key("[UNTRUSTED]"):
804 GenShadow(l,OutDir+"shadow");
806 # Link in global things
807 DoLink(GlobalDir,OutDir,"ssh-rsa-shadow");
808 DoLink(GlobalDir,OutDir,"markers");
809 DoLink(GlobalDir,OutDir,"mail-forward.cdb");
810 DoLink(GlobalDir,OutDir,"debianhosts");
811 DoLink(GlobalDir,OutDir,"ssh_known_hosts");
812 DoLink(GlobalDir,OutDir,"mail-disable");
813 DoLink(GlobalDir,OutDir,"mail-greylist");
814 DoLink(GlobalDir,OutDir,"mail-callout");
815 DoLink(GlobalDir,OutDir,"mail-rbl");
816 DoLink(GlobalDir,OutDir,"mail-rhsbl");
817 DoLink(GlobalDir,OutDir,"mail-whitelist");
820 DoLink(GlobalDir,OutDir,"forward-alias");
822 if ExtraList.has_key("[DNS]"):
823 GenDNS(l,OutDir+"dns-zone",Split[1]);
824 GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
826 if ExtraList.has_key("[BSMTP]"):
827 GenBSMTP(l,OutDir+"bsmtp",Split[1])
829 if ExtraList.has_key("[PRIVATE]"):
830 DoLink(GlobalDir,OutDir,"debian-private")