...
 
Commits (5)
......@@ -16,6 +16,10 @@ userdir-ldap (0.3.97) UNRELEASED; urgency=medium
* ud-generate: use subprocess.Popen instead of os.popen in GenCDB.
* Use "not in" operator in various places ("foo not in bar" instead of "not
foo in bar").
* ud-mailgate: use subprocess.Popen instead of os.popen.
* Use "foo is None" instead of "foo == None".
* Use "foo is not None" instead of "foo != None".
* Stop using string exceptions. They were removed in python 2.6.
-- Peter Palfrader <weasel@debian.org> Sat, 06 Apr 2019 22:04:34 +0200
......
......@@ -21,20 +21,20 @@
# entry. This little script updates an ldap from old to new.
import string, re, time, ldap, getopt, sys, os, pwd, posix, socket, base64, shutil, errno, tarfile, grp
from userdir_ldap import *;
from userdir_ldap import *
UUID_FORMAT = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
# Connect to the ldap server
l = connectLDAP()
F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r")
Pass = F.readline().strip().split(" ")
F.close();
l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
F.close()
l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1])
PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"sudoPassword=*", ["uid","sudoPassword"]);
PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"sudoPassword=*", ["uid","sudoPassword"])
if PasswdAttrs == None:
raise "No Users";
raise Exception("No Users")
for x in PasswdAttrs:
if not x[1].has_key('sudoPassword'):
......@@ -53,7 +53,7 @@ for x in PasswdAttrs:
# ok old format
oldformat = 'confirmed:'+make_hmac(':'.join(['password-is-confirmed', uuid, hosts, cryptedpass]))
newformat = 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', x[1]['uid'][0], uuid, hosts, cryptedpass);
newformat = 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', x[1]['uid'][0], uuid, hosts, cryptedpass)
if status == oldformat:
print "Updating sudo password entry for %s."%(uid)
......@@ -69,6 +69,6 @@ for x in PasswdAttrs:
else:
Rec.append((ldap.MOD_ADD, 'sudoPassword', line))
Dn = "uid=" + uid + "," + BaseDn;
l.modify_s(Dn,Rec);
Dn = "uid=" + uid + "," + BaseDn
l.modify_s(Dn,Rec)
......@@ -31,7 +31,6 @@ from userdir_gpg import *;
EX_TEMPFAIL = 75;
EX_PERMFAIL = 65; # EX_DATAERR
Error = 'Message Error';
# Configuration
ReplayCacheFile = None;
......@@ -42,6 +41,9 @@ Phrases = None;
AllowMIME = 1;
Verbose = 0;
class MessageError(Exception):
pass
def verbmsg(msg):
if Verbose:
sys.stderr.write(msg + "\n")
......@@ -63,9 +65,9 @@ def CheckLDAP(FingerPrint):
verbmsg("Processing fingerprint %s" % FingerPrint)
Attrs = l.search_s(LDAPDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=" + FingerPrint);
if len(Attrs) == 0:
raise Error, "Key not found"
raise MessageError("Key not found")
if len(Attrs) != 1:
raise Error, "Oddly your key fingerprint is assigned to more than one account.."
raise MessageError("Oddly your key fingerprint is assigned to more than one account..")
gidnumber_found = 0;
for key in Attrs[0][1].keys():
......@@ -73,16 +75,16 @@ def CheckLDAP(FingerPrint):
gidnumber_found = 1
if (gidnumber_found != 1):
raise Error, "No gidnumber in attributes for fingerprint %s" % FingerPrint
raise MessageError("No gidnumber in attributes for fingerprint %s" % FingerPrint)
# Look for the group with the gid of the user
GAttr = l.search_s(LDAPDn,ldap.SCOPE_ONELEVEL,"(&(objectClass=debianGroup)(gidnumber=%s))" % Attrs[0][1]["gidNumber"][0], ["gid"])
if len(GAttr) == 0:
raise Error, "Database inconsistency found: main group for account not found in database"
raise MessageError("Database inconsistency found: main group for account not found in database")
# See if the group membership is OK
# Only if a group was given on the commandline
if GroupMember != None:
if GroupMember is not None:
Hit = 0;
# Check primary group first
if GAttr[0][1]["gid"][0] == GroupMember:
......@@ -93,7 +95,7 @@ def CheckLDAP(FingerPrint):
if x == GroupMember:
Hit = 1;
if Hit != 1:
raise Error, "You don't have %s group permissions."%(GroupMember);
raise MessageError("You don't have %s group permissions."%(GroupMember))
# Start of main program
# Process options
......@@ -123,7 +125,7 @@ MsgID = None;
try:
# Startup the replay cache
ErrType = EX_TEMPFAIL;
if ReplayCacheFile != None:
if ReplayCacheFile is not None:
ErrMsg = "Failed to initialize the replay cache:";
RC = ReplayCache(ReplayCacheFile);
......@@ -137,37 +139,37 @@ try:
verbmsg("Processing message %s" % MsgID)
Msg = GetClearSig(mail,1);
if AllowMIME == 0 and Msg[1] != 0:
raise Error, "PGP/MIME disallowed";
raise MessageError("PGP/MIME disallowed")
ErrMsg = "Message is not PGP signed:"
if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1:
raise Error, "No PGP signature";
raise MessageError("No PGP signature")
# Check the signature
ErrMsg = "Unable to check the signature or the signature was invalid:";
pgp = GPGCheckSig2(Msg[0])
if not pgp.ok:
raise UDFormatError, pgp.why
raise UDFormatError(pgp.why)
if pgp.text is None:
raise UDFormatError, "Null signature text"
raise UDFormatError("Null signature text")
# Check the signature against the replay cache
if ReplayCacheFile != None:
if ReplayCacheFile is not None:
RC.process(pgp.sig_info)
# Do LDAP stuff
if LDAPDn != None:
if LDAPDn is not None:
CheckLDAP(pgp.key_fpr)
ErrMsg = "Verifying message:";
if Phrases != None:
if Phrases is not None:
F = open(Phrases,"r");
while 1:
Line = F.readline();
if Line == "": break;
if pgp.text.find(Line.strip()) == -1:
raise Error,"Phrase '%s' was not found" % (Line.strip())
raise MessageError("Phrase '%s' was not found" % (Line.strip()))
except:
ErrMsg = "[%s] \"%s\" \"%s %s\"\n"%(Now,MsgID,ErrMsg,sys.exc_value);
......
......@@ -49,7 +49,7 @@ while(1):
if Line != "":
# Glob similar lines
Split = re.split("[:\n]",Line);
if User == None:
if User is None:
User = Split[0];
if Split[0] == User:
Set.append(Split[1].strip());
......
......@@ -46,14 +46,14 @@ def TryGPG(mail):
# Try to guess the name from the email address
def TryMatcher(mail):
Sender = mail["From"];
if Sender == None:
if Sender is None:
return None;
# Split up the address and invoke the matcher routine
UID = GetUID(l,SplitEmail(Sender));
if UID[0] == None:
if UID[1] == None or len(UID[1]) == 0:
if UID[0] is None:
if UID[1] is None or len(UID[1]) == 0:
return None;
# Print out an error message
......@@ -72,7 +72,7 @@ for (switch, val) in options:
Debug = "";
# Open the log files
if Debug == None:
if Debug is None:
MainLog = open(Ech_MainLog,"a+",0);
ErrLog = open(Ech_ErrorLog,"a+",0);
else:
......@@ -96,7 +96,7 @@ try:
ErrMsg = "An error occured while performing the LDAP lookup";
global l;
l = connectLDAP()
if Debug == None:
if Debug is None:
F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
AccessPass = F.readline().strip().split(" ")
l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
......@@ -108,7 +108,7 @@ try:
ErrType = EX_TEMPFAIL;
ErrMsg = "An error occured while trying GPG decoding";
User = TryGPG(mail);
if User == None:
if User is None:
ErrMsg = "An error occured while trying Matcher decoding";
User = TryMatcher(mail);
......@@ -117,12 +117,12 @@ try:
if not List: List = "-";
# Tada, write a log message
if User != None:
if User is not None:
Msg = "[%s] \"%s\" \"%s\" \"%s\""%(Now,User[2],List,MsgID);
MainLog.write("%s %s %s\n"%(User[0],User[1],Msg));
Dn = "uid=" + User[0] + "," + BaseDn;
Rec = [(ldap.MOD_REPLACE,"activity-%s"%(User[1]),Msg)];
if Debug == None:
if Debug is None:
l.modify_s(Dn,Rec);
else:
print Rec;
......
......@@ -81,10 +81,10 @@ while(1):
Split = Line.split(":")
if len(Split) >= 8 and Split[0] == "pub":
if FingerPrint != None and UID != None:
if FingerPrint is not None and UID is not None:
for x in Emails:
Match = AddressSplit.match(x);
if Match == None:
if Match is None:
continue;
Groups = Match.groups();
Email = Groups[1]+'@'+Groups[2];
......
......@@ -21,7 +21,7 @@ while (1):
if File == "":
break;
# Attempt to determine the UID
# Attempt to determine the UID
try:
User = pwd.getpwuid(os.stat(File)[stat.ST_UID])[0];
except KeyError:
......@@ -37,13 +37,13 @@ while (1):
break;
if Line2[0] == '#' or Line2[0] == '\n':
continue;
if Line == None:
if Line is None:
Line = Line2;
else:
break;
# If we got more than one line or no lines at all it is invalid
if Line == None or Line == "" or Line2 != "":
if Line is None or Line == "" or Line2 != "":
print "Invalid1", File;
continue;
......@@ -55,7 +55,7 @@ while (1):
# Split off the address part
Address = AddressSplit.match(Line);
if Address == None:
if Address is None:
# Or parse a qmail adddress..
Address = Line;
if Address[0] == '&':
......
......@@ -184,9 +184,9 @@ def IsInGroup(account, allowed, current_host):
return False
def Die(File, F, Fdb):
if F != None:
if F is not None:
F.close()
if Fdb != None:
if Fdb is not None:
Fdb.close()
try:
os.remove(File + ".tmp")
......@@ -198,10 +198,10 @@ def Die(File, F, Fdb):
pass
def Done(File, F, Fdb):
if F != None:
if F is not None:
F.close()
os.rename(File + ".tmp", File)
if Fdb != None:
if Fdb is not None:
Fdb.close()
os.rename(File + ".tdb.tmp", File + ".tdb")
......@@ -309,7 +309,7 @@ def GenShadowSudo(accounts, File, untrusted, current_host):
if 'sudoPassword' in a:
for entry in a['sudoPassword']:
Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*-]+) ([^ ]+)$').match(entry)
if Match == None:
if Match is None:
continue
uuid = Match.group(1)
status = Match.group(2)
......@@ -848,7 +848,7 @@ def GenDNS(accounts, File):
F.write(Line)
Host = Split[0] + DNSZone
if BSMTPCheck.match(Line) != None:
if BSMTPCheck.match(Line) is not None:
F.write("; Has BSMTP\n")
# Write some identification information
......@@ -918,7 +918,7 @@ def ExtractDNSInfo(x):
Algorithm = 2
if key_prefix == 'ssh-ed25519':
Algorithm = 4
if Algorithm == None:
if Algorithm is None:
continue
# and more from the registry
sshfp_digest_codepoints = [ (1, 'sha1'), (2, 'sha256') ]
......@@ -989,7 +989,7 @@ def GenBSMTP(accounts, File, HomePrefix):
Line = " ".join(Split) + "\n"
Host = Split[0] + DNSZone
if BSMTPCheck.match(Line) != None:
if BSMTPCheck.match(Line) is not None:
F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
a['uid'], HomePrefix, a['uid'], Host))
......@@ -1142,7 +1142,7 @@ def get_hosts(ldap_conn):
"mXRecord", "ipHostNumber", "dnsTTL", "machine", "architecture",
"sshfpHostname"])
if HostAttrs == None:
if HostAttrs is None:
raise UDEmptyList, "No Hosts"
HostAttrs.sort(lambda x, y: cmp((GetAttr(x, "hostname")).lower(), (GetAttr(y, "hostname")).lower()))
......
......@@ -95,8 +95,8 @@ def load_keys_from_gpg(keyrings):
continue
keys[fingerprint] = pgp_uid
if Keys.close() != None:
raise "Error","GPG failed"
if Keys.close() is not None:
raise Exception("GPG failed")
return keys
......@@ -177,9 +177,9 @@ for fpr in pgpkeys:
continue;
UID = GetUID(l,SplitEmail(pgp_uid),UnknownMap);
if UID[0] == None:
if UID[0] is None:
print "Unassigned key in keyrings: %s, belonging to %s"%(fpr, pgp_uid)
if UID[1] != None:
if UID[1] is not None:
for x in UID[1]: print x;
print "MISSING " + fpr;
continue;
......
......@@ -331,10 +331,11 @@ def DoSSH(Str, Attrs, badkeys, uid):
Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
ErrReply = TemplateSubst(Subst, open(TemplatesDir + "admin-info", "r").read())
Child = os.popen("/usr/sbin/sendmail -t", "w")
Child.write(ErrReplyHead)
Child.write(ErrReply)
if Child.close() is not None:
Child = subprocess.Popen(['/usr/sbin/sendmail', '-t'], stdin=subprocess.PIPE)
Child.stdin.write(ErrReplyHead)
Child.stdin.write(ErrReply)
Child.stdin.close()
if Child.wait() != 0:
raise UDExecuteError("Sendmail gave a non-zero return code")
except Exception:
sys.exit(EX_TEMPFAIL)
......
......@@ -37,7 +37,7 @@ while (1):
break;
if Line[0] == '#' or Line[0] == '\n':
continue;
if SSHAuthSplit.match(Line) == None:
if SSHAuthSplit.match(Line) is None:
print "Bad line", File;
else:
Lines.append(Line);
......
......@@ -180,7 +180,7 @@ while 1:
cn = GetAttr(Attrs[0],"cn");
sn = GetAttr(Attrs[0],"sn");
mn = GetAttr(Attrs[0],"mn");
if privsub == None or privsub == "":
if privsub is None or privsub == "":
privsub = " ";
break;
else:
......@@ -267,8 +267,8 @@ if Update == 0 or ForceMail == 1:
CryptedPass = GPGEncrypt("Your new password is '" + Password + "'\n",\
"0x"+Keys[0][1],UsePGP2);
Password = None;
if CryptedPass == None:
raise "Error","Password Encryption failed"
if CryptedPass is None:
raise Exception("Password Encryption failed")
else:
Pass = HashPass(Password);
CryptedPass = "Your password has been set to the previously agreed value.";
......@@ -376,7 +376,7 @@ else:
(ldap.MOD_REPLACE,"shadowExpire","")];
if privsub != " ":
Rec.append((ldap.MOD_REPLACE,"privateSub",privsub));
if Pass != None:
if Pass is not None:
Rec.append((ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass));
# Do it
l.modify_s(Dn,Rec);
......@@ -397,8 +397,8 @@ Reply = TemplateSubst(Subst,open(templatepath, "r").read())
Child = os.popen("/usr/sbin/sendmail -t","w");
#Child = os.popen("cat","w");
Child.write(Reply);
if Child.close() != None:
raise Error, "Sendmail gave a non-zero return code";
if Child.close() is not None:
raise Exception("Sendmail gave a non-zero return code")
# vim:set et:
# vim:set ts=3:
......
......@@ -126,7 +126,7 @@ ErrType = EX_TEMPFAIL;
try:
# Startup the replay cache
ErrType = EX_TEMPFAIL;
if ReplayCacheFile != None:
if ReplayCacheFile is not None:
ErrMsg = "Failed to initialize the replay cache:";
RC = ReplayCache(ReplayCacheFile);
RC.Clean();
......@@ -145,10 +145,10 @@ try:
ErrMsg = "Unable to check the signature or the signature was invalid:";
Res = GPGCheckSig(Msg[0]);
if Res[0] != None:
if Res[0] is not None:
raise Error, Res[0];
if Res[3] == None:
if Res[3] is None:
raise Error, "Null signature text";
# Extract the plain message text in the event of mime encoding
......@@ -164,24 +164,24 @@ try:
PlainText = Res[3];
# Check the signature against the replay cache
if ReplayCacheFile != None:
if ReplayCacheFile is not None:
ErrMsg = "The replay cache rejected your message. Check your clock!";
Rply = RC.Check(Res[1]);
if Rply != None:
if Rply is not None:
raise Error, Rply;
RC.Add(Res[1]);
# Do LDAP stuff
if LDAPDn != None:
if LDAPDn is not None:
CheckLDAP(Res[2][1]);
# Determine the sender address
ErrType = EX_PERMFAIL;
ErrMsg = "A problem occured while trying to formulate the reply";
Sender = Email.getheader("Reply-To");
if Sender == None:
if Sender is None:
Sender = Email.getheader("From");
if Sender == None:
if Sender is None:
raise Error, "Unable to determine the sender's address";
# Setup the environment
......@@ -195,7 +195,7 @@ try:
# Invoke the child
Child = os.popen(" ".join(arguments),"w");
Child.write(PlainText);
if Child.close() != None:
if Child.close() is not None:
raise Error, "Child gave a non-zero return code";
except:
......@@ -219,7 +219,7 @@ except:
# Try to send the bounce
try:
if ErrorTemplate != None:
if ErrorTemplate is not None:
ErrReply = TemplateSubst(Subst,open(ErrorTemplate,"r").read());
else:
ErrReply = "\n"+str(Subst)+"\n";
......@@ -227,7 +227,7 @@ except:
Child = os.popen("/usr/sbin/sendmail -t","w");
Child.write(ErrReplyHead);
Child.write(ErrReply);
if Child.close() != None:
if Child.close() is not None:
raise Error, "Sendmail gave a non-zero return code";
except:
sys.exit(EX_TEMPFAIL);
......
......@@ -127,7 +127,7 @@ def GetClearSig(Msg, Paranoid=0, lax_multipart=False):
# original signed block [needs to convert to \r\n]
Output = "-----BEGIN PGP SIGNED MESSAGE-----\r\n";
# Semi-evil hack to get the proper hash type inserted in the message
if Msg.get_param('micalg') != None:
if Msg.get_param('micalg') is not None:
Output = Output + "Hash: SHA1,%s\r\n"%(Msg.get_param('micalg')[4:].upper())
Output = Output + "\r\n";
Output = Output + Signed.as_string().replace("\n-","\n- -") + "\n" + Signature.get_payload(decode=True)
......@@ -216,7 +216,7 @@ def GPGWriteFilter(Program,Options,Message):
InPipe[0] = -1;
# Send the message
if Message != None:
if Message is not None:
try:
os.write(InPipe[1],Message);
except:
......@@ -244,12 +244,14 @@ def GPGWriteFilter(Program,Options,Message):
Output.close();
GPGText.close();
# This takes a text passage, a destination and a flag indicating the
# compatibility to use and returns an encrypted message to the recipient.
# It is best if the recipient is specified using the hex key fingerprint
# of the target, ie 0x64BE1319CCF6D393BF87FF9358A6D4EE
def GPGEncrypt(Message,To,PGP2):
Error = "KeyringError"
class KeyringError(Exception): pass
# Encrypt using the PGP5 block encoding and with the PGP5 option set.
# This will handle either RSA or DSA/DH asymetric keys.
# In PGP2 compatible mode IDEA and rfc1991 encoding are used so that
......@@ -257,11 +259,11 @@ def GPGEncrypt(Message,To,PGP2):
# can read a message encrypted with blowfish and RSA.
searchkey = GPGKeySearch(To);
if len(searchkey) == 0:
raise Error, "No key found matching %s"%(To);
raise KeyringError("No key found matching %s"%(To))
elif len(searchkey) > 1:
raise Error, "Multiple keys found matching %s"%(To);
raise KeyringError("Multiple keys found matching %s"%(To))
if searchkey[0][4].find("E") < 0:
raise Error, "Key %s has no encryption capability - are all encryption subkeys expired or revoked? Are there any encryption subkeys?"%(To);
raise KeyringError("Key %s has no encryption capability - are all encryption subkeys expired or revoked? Are there any encryption subkeys?"%(To))
if PGP2 == 0:
try:
......@@ -272,7 +274,7 @@ def GPGEncrypt(Message,To,PGP2):
Text = Res[2].read();
return Text;
finally:
if Res != None:
if Res is not None:
Res[1].close();
Res[2].close();
else:
......@@ -294,7 +296,7 @@ def GPGEncrypt(Message,To,PGP2):
os.unlink(TmpName);
except:
pass;
if Res != None:
if Res is not None:
Res[1].close();
Res[2].close();
......@@ -343,7 +345,7 @@ def GPGCheckSig(Message):
# Good signature response
if Split[1] == "GOODSIG":
# Just in case GPG returned a bad signal before this (bug?)
if Why == None:
if Why is None:
GoodSig = 1;
KeyID = Split[2];
Owner = ' '.join(Split[3:])
......@@ -416,21 +418,21 @@ def GPGCheckSig(Message):
Text = Res[2].read();
# A gpg failure is an automatic bad signature
if Exit[1] != 0 and Why == None:
if Exit[1] != 0 and Why is None:
GoodSig = 0;
Why = "GPG execution returned non-zero exit status: " + str(Exit[1]);
if GoodSig == 0 and (Why == None or len(Why) == 0):
if GoodSig == 0 and (Why is None or len(Why) == 0):
Why = "Checking Failed";
# Try to decide if this message was sent using PGP2
PGP2Message = 0;
if (re.search("-----[\n\r][\n\r]?Version: 2\\.",Message) != None):
if (re.search("-----[\n\r][\n\r]?Version: 2\\.",Message) is not None):
PGP2Message = 1;
return (Why,(SigId,Date,KeyFinger),(KeyID,KeyFinger,Owner,0,PGP2Message),Text);
finally:
if Res != None:
if Res is not None:
Res[1].close();
Res[2].close();
......@@ -529,7 +531,7 @@ def GPGKeySearch(SearchCriteria):
continue
finally:
if Strm != None:
if Strm is not None:
Strm.close()
return Result
......@@ -585,7 +587,7 @@ class ReplayCache:
# Check a signature. 'sig' is a 3 tuple that has the sigId, date and
# key ID
def Check(self,Sig):
if Sig[0] == None or Sig[1] == None or Sig[2] == None:
if Sig[0] is None or Sig[1] is None or Sig[2] is None:
return "Invalid signature";
if int(Sig[1]) > time.time() + self.FutureCutOff:
return "Signature has a time too far in the future";
......@@ -598,7 +600,7 @@ class ReplayCache:
# Add a signature, the sig is the same as is given to Check
def Add(self,Sig):
if Sig[0] == None or Sig[1] == None:
if Sig[0] is None or Sig[1] is None:
raise RuntimeError,"Invalid signature";
if Sig[1] < time.time() - self.CleanCutOff:
return;
......
......@@ -244,7 +244,7 @@ def HashPass(Password):
Salt = Salt + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)]
Pass = crypt.crypt(Password, Salt)
if len(Pass) < 14:
raise "Password Error", "MD5 password hashing failed, not changing the password!"
raise Exception("MD5 password hashing failed, not changing the password!")
return Pass
......