3 # Generates passwd, shadow and group files from the ldap directory.
5 # Copyright (c) 2000-2001 Jason Gunthorpe <jgg@debian.org>
6 # Copyright (c) 2001-2003 Ryan Murray <rmurray@debian.org>
7 # Copyright (c) 2003-2004 James Troup <troup@debian.org>
8 # Copyright (c) 2004-2005 Joey Schulze <joey@infodrom.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;
25 from userdir_ldap import *;
35 EmailCheck = re.compile("^([^ <>@]+@[^ ,<>@]+)?$");
36 BSMTPCheck = re.compile(".*mx 0 (klecker|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):
256 OldMask = os.umask(0022);
257 F = open(File + ".tmp","w",0644);
260 # Fetch all the users
262 if PasswdAttrs == None:
265 # Write out the email address for each user
266 for x in PasswdAttrs:
267 if x[1].has_key("emailForward") == 0 or IsInGroup(x) == 0:
270 # Do not allow people to try to buffer overflow busted parsers
271 if len(GetAttr(x,"emailForward")) > 200:
274 # Check the forwarding address
275 if EmailCheck.match(GetAttr(x,"emailForward")) == None:
277 Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailForward"));
278 Line = Sanitize(Line) + "\n";
281 # Oops, something unspeakable happened.
287 def GenAllForward(l,File):
290 OldMask = os.umask(0022);
291 Fdb = os.popen("cdbmake %s %s.tmp"%(File,File),"w");
294 # Fetch all the users
296 if PasswdAttrs == None:
299 # Write out the email address for each user
300 for x in PasswdAttrs:
301 if x[1].has_key("emailForward") == 0:
304 # Do not allow people to try to buffer overflow busted parsers
305 Forward = GetAttr(x,"emailForward");
306 if len(Forward) > 200:
309 # Check the forwarding address
310 if EmailCheck.match(Forward) == None:
313 User = GetAttr(x,"uid");
314 Fdb.write("+%d,%d:%s->%s\n"%(len(User),len(Forward),User,Forward));
316 # Oops, something unspeakable happened.
320 if Fdb.close() != None:
321 raise "cdbmake gave an error";
323 # Generate the anon XEarth marker file
324 def GenMarkers(l,File):
328 F = open(File + ".tmp","w");
331 # Fetch all the users
333 if PasswdAttrs == None:
336 # Write out the position for each user
337 for x in PasswdAttrs:
338 if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
341 Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
342 Line = Sanitize(Line) + "\n";
347 # Oops, something unspeakable happened.
353 # Generate the debian-private subscription list
354 def GenPrivate(l,File):
358 F = open(File + ".tmp","w");
361 # Fetch all the users
363 if PasswdAttrs == None:
366 # Write out the position for each user
367 for x in PasswdAttrs:
368 if x[1].has_key("privateSub") == 0:
371 # If the account is locked, do not write it
372 if (string.find(GetAttr(x,"userPassword"),"*LK*") != -1):
375 # If the account has no PGP key, do not write it
376 if x[1].has_key("keyFingerPrint") == 0:
379 # Must be in the Debian group (yuk, hard coded for now)
380 if GetAttr(x,"gidNumber") != "800":
384 Line = "%s"%(GetAttr(x,"privateSub"));
385 Line = Sanitize(Line) + "\n";
390 # Oops, something unspeakable happened.
396 # Generate the DNS Zone file
397 def GenDNS(l,File,HomePrefix):
400 F = open(File + ".tmp","w");
402 # Fetch all the users
404 if PasswdAttrs == None:
407 # Write out the zone file entry for each user
408 for x in PasswdAttrs:
409 if x[1].has_key("dnsZoneEntry") == 0:
412 F.write("; %s\n"%(EmailAddress(x)));
413 for z in x[1]["dnsZoneEntry"]:
414 Split = string.split(string.lower(z));
415 if string.lower(Split[1]) == 'in':
416 for y in range(0,len(Split)):
419 Line = string.join(Split," ") + "\n";
422 Host = Split[0] + DNSZone;
423 if BSMTPCheck.match(Line) != None:
424 F.write("; Has BSMTP\n");
426 # Write some identification information
427 if string.lower(Split[2]) == "a":
428 Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
429 for y in x[1]["keyFingerPrint"]:
430 Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
433 Line = "; Err %s"%(str(Split));
438 F.write("; Errors\n");
441 # Oops, something unspeakable happened.
447 # Generate the BSMTP file
448 def GenBSMTP(l,File,HomePrefix):
451 F = open(File + ".tmp","w");
453 # Fetch all the users
455 if PasswdAttrs == None:
458 # Write out the zone file entry for each user
459 for x in PasswdAttrs:
460 if x[1].has_key("dnsZoneEntry") == 0:
463 for z in x[1]["dnsZoneEntry"]:
464 Split = string.split(string.lower(z));
465 if string.lower(Split[1]) == 'in':
466 for y in range(0,len(Split)):
469 Line = string.join(Split," ") + "\n";
471 Host = Split[0] + DNSZone;
472 if BSMTPCheck.match(Line) != None:
473 F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
474 GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
477 F.write("; Errors\n");
480 # Oops, something unspeakable happened.
486 # Generate the shadow list
487 def GenSSHKnown(l,File):
490 OldMask = os.umask(0022);
491 F = open(File + ".tmp","w",0644);
494 # Fetch all the hosts
495 HostKeys = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
496 ["hostname","sshRSAHostKey"]);
502 if x[1].has_key("hostname") == 0 or \
503 x[1].has_key("sshRSAHostKey") == 0:
505 Host = GetAttr(x,"hostname");
506 SHost = string.find(Host,".");
507 for I in x[1]["sshRSAHostKey"]:
509 Line = "%s,%s %s" %(Host,socket.gethostbyname(Host),I);
511 Line = "%s,%s,%s %s" %(Host,Host[0:SHost],socket.gethostbyname(Host),I);
512 Line = Sanitize(Line) + "\n";
514 # Oops, something unspeakable happened.
521 # Connect to the ldap server
522 l = ldap.open(LDAPServer);
523 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
524 Pass = string.split(string.strip(F.readline())," ");
526 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
528 # Fetch all the groups
530 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
531 ["gid","gidNumber"]);
533 # Generate the GroupMap and GroupIDMap
535 if x[1].has_key("gidNumber") == 0:
537 GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
539 # Fetch all the users
540 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
541 ["uid","uidNumber","gidNumber","supplementaryGid",\
542 "gecos","loginShell","userPassword","shadowLastChange",\
543 "shadowMin","shadowMax","shadowWarning","shadowinactive",
544 "shadowexpire","emailForward","latitude","longitude",\
545 "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
546 "keyFingerPrint","privateSub"]);
548 # Open the control file
549 if len(sys.argv) == 1:
550 F = open(GenerateConf,"r");
552 F = open(sys.argv[1],"r")
554 # Generate global things
555 GlobalDir = GenerateDir+"/";
556 GenSSHShadow(l,GlobalDir+"ssh-rsa-shadow");
557 GenAllForward(l,GlobalDir+"mail-forward.cdb");
558 GenMarkers(l,GlobalDir+"markers");
559 GenPrivate(l,GlobalDir+"debian-private");
560 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
563 GenForward(l,GlobalDir+"forward-alias");
569 Line = string.strip(Line);
575 Split = string.split(Line," ");
576 OutDir = GenerateDir + '/' + Split[0] + '/';
577 try: os.mkdir(OutDir);
580 # Get the group list and convert any named groups to numerics
588 if GroupIDMap.has_key(I):
589 GroupList[str(GroupIDMap[I])] = None;
594 CurrentHost = Split[0];
597 GenPasswd(l,OutDir+"passwd",Split[1]);
599 GenGroup(l,OutDir+"group");
600 if ExtraList.has_key("[UNTRUSTED]"):
602 GenShadow(l,OutDir+"shadow");
604 # Link in global things
605 DoLink(GlobalDir,OutDir,"ssh-rsa-shadow");
606 DoLink(GlobalDir,OutDir,"markers");
607 DoLink(GlobalDir,OutDir,"mail-forward.cdb");
608 DoLink(GlobalDir,OutDir,"ssh_known_hosts");
611 DoLink(GlobalDir,OutDir,"forward-alias");
613 if ExtraList.has_key("[DNS]"):
614 GenDNS(l,OutDir+"dns-zone",Split[1]);
616 if ExtraList.has_key("[BSMTP]"):
617 GenBSMTP(l,OutDir+"bsmtp",Split[1]);
619 if ExtraList.has_key("[PRIVATE]"):
620 DoLink(GlobalDir,OutDir,"debian-private");