--- /dev/null
+#!/usr/bin/env python
+# -*- mode: python -*-
+#
+# Check and decode PGP signed emails.
+# This script implements a wrapper around another program. It takes a mail
+# on stdin and processes off a PGP signature, verifying it and seperating
+# out the checked plaintext. It then invokes a sub process and feeds it
+# the verified plain text and sets environment vairables indicating the
+# result of the PGP check. If PGP checking fails then the subprocess is
+# is never run and a bounce message is generated. The wrapper can understand
+# PGP-MIME and all signatures supported by GPG. It completely decodes
+# PGP-MIME before running the subprocess. It also can do optional
+# anti-replay checking on the signatures.
+#
+# If enabled it can also do LDAP checking to determine the uniq UID owner
+# of the key.
+#
+# Options:
+# -r Replay cache file, if unset replay checking is disabled
+# -e Bounce error message template file, if unset very ugly bounces are
+# made
+# -k Colon seperated list of keyrings to use
+# -a Reply to address (mail daemon administrator)
+# -d LDAP search base DN
+# -l LDAP server
+# -m Email address to use when prettying up LDAP_EMAIL
+#
+# It exports the following environment variables:
+# LDAP_EMAIL="Adam Di Carlo <aph@debian.org>"
+# LDAP_UID="aph"
+# PGP_FINGERPRINT="E21E5D13FAD42A54F1AA5A00D801CE55"
+# PGP_KEYID="8FFC405EFD5A67CD"
+# PGP_KEYNAME="Adam Di Carlo <aph@debian.org> "
+# SENDER (from mailer - envelope sender for bounces)
+# REPLYTO (generated from message headers)
+#
+# Typical Debian invokation may look like:
+# ./gpgwrapper -k /usr/share/keyrings/debian-keyring.gpg:/usr/share/keyrings/debian-keyring.pgp \
+# -d ou=users,dc=debian,dc=org -l db.debian.org \
+# -m debian.org -a admin@db.debian.org \
+# -e /etc/userdir-ldap/templtes/error-reply -- test.sh
+
+import sys, traceback, time, os;
+import string, pwd, getopt;
+from userdir_gpg import *;
+
+EX_TEMPFAIL = 75;
+EX_PERMFAIL = 65; # EX_DATAERR
+Error = 'Message Error';
+ReplyTo = "admin@db";
+
+# Configuration
+ReplayCacheFile = None;
+ErrorTemplate = None;
+LDAPDn = None;
+LDAPServer = None;
+EmailAppend = "";
+
+# Safely get an attribute from a tuple representing a dn and an attribute
+# list. It returns the first attribute if there are multi.
+def GetAttr(DnRecord,Attribute,Default = ""):
+ try:
+ return DnRecord[1][Attribute][0];
+ except IndexError:
+ return Default;
+ except KeyError:
+ return Default;
+ return Default;
+
+# Return a printable email address from the attributes.
+def EmailAddress(DnRecord):
+ cn = GetAttr(DnRecord,"cn");
+ sn = GetAttr(DnRecord,"sn");
+ uid = GetAttr(DnRecord,"uid");
+ if cn == "" and sn == "":
+ return "<" + uid + "@" + EmailAppend + ">";
+ return cn + " " + sn + " <" + uid + "@" + EmailAppend + ">"
+
+# Match the key fingerprint against an LDAP directory
+def CheckLDAP(FingerPrint):
+ import ldap;
+
+ # Connect to the ldap server
+ global ErrTyp, ErrMsg;
+ ErrType = EX_TEMPFAIL;
+ ErrMsg = "An error occured while performing the LDAP lookup";
+ global l;
+ l = ldap.open(LDAPServer);
+ l.simple_bind_s("","");
+
+ # Search for the matching key fingerprint
+ Attrs = l.search_s(LDAPDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=" + FingerPrint);
+ if len(Attrs) == 0:
+ raise Error, "Key not found"
+ if len(Attrs) != 1:
+ raise Error, "Oddly your key fingerprint is assigned to more than one account.."
+
+ os.environ["LDAP_UID"] = GetAttr(Attrs[0],"uid");
+ os.environ["LDAP_EMAIL"] = EmailAddress(Attrs[0]);
+
+# Start of main program
+# Process options
+(options, arguments) = getopt.getopt(sys.argv[1:], "r:e:k:a:d:l:m:");
+for (switch, val) in options:
+ if (switch == '-r'):
+ ReplayCacheFile = val;
+ elif (switch == '-e'):
+ ErrorTempalte = val;
+ elif (switch == '-k'):
+ SetKeyrings(string.split(val,":"));
+ elif (switch == '-a'):
+ ReplyTo = val;
+ elif (switch == '-d'):
+ LDAPDn = val;
+ elif (switch == '-l'):
+ LDAPServer = val;
+ elif (switch == '-m'):
+ EmailAppend = val;
+
+# Drop messages from a mailer daemon. (empty sender)
+if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
+ sys.exit(0);
+
+ErrMsg = "Indeterminate Error";
+ErrType = EX_TEMPFAIL;
+try:
+ # Startup the replay cache
+ ErrType = EX_TEMPFAIL;
+ if ReplayCacheFile != None:
+ ErrMsg = "Failed to initialize the replay cache:";
+ RC = ReplayCache(ReplayCacheFile);
+ RC.Clean();
+
+ # Get the email
+ ErrType = EX_PERMFAIL;
+ ErrMsg = "Failed to understand the email or find a signature:";
+ Email = mimetools.Message(sys.stdin,0);
+ Msg = GetClearSig(Email);
+
+ ErrMsg = "Message is not PGP signed:"
+ if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1:
+ raise Error, "No PGP signature";
+
+ # Check the signature
+ ErrMsg = "Unable to check the signature or the signature was invalid:";
+ Res = GPGCheckSig(Msg[0]);
+
+ if Res[0] != None:
+ raise Error, Res[0];
+
+ if Res[3] == None:
+ raise Error, "Null signature text";
+
+ # Extract the plain message text in the event of mime encoding
+ global PlainText;
+ ErrMsg = "Problem stripping MIME headers from the decoded message"
+ if Msg[1] == 1:
+ try:
+ Index = string.index(Res[3],"\n\n") + 2;
+ except ValueError:
+ Index = string.index(Res[3],"\n\r\n") + 3;
+ PlainText = Res[3][Index:];
+ else:
+ PlainText = Res[3];
+
+ # Check the signature against the replay cache
+ if ReplayCacheFile != None:
+ ErrMsg = "The replay cache rejected your message. Check your clock!";
+ Rply = RC.Check(Res[1]);
+ if Rply != None:
+ raise Error, Rply;
+ RC.Add(Res[1]);
+
+ # Do LDAP stuff
+ if LDAPDn != 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:
+ Sender = Email.getheader("From");
+ if Sender == None:
+ raise Error, "Unable to determine the sender's address";
+
+ # Setup the environment
+ ErrType = EX_TEMPFAIL;
+ ErrMsg = "Problem calling the child process"
+ os.environ["PGP_KEYID"] = Res[2][0];
+ os.environ["PGP_FINGERPRINT"] = Res[2][1];
+ os.environ["PGP_KEYNAME"] = Res[2][2];
+ os.environ["REPLYTO"] = Sender;
+
+ # Invoke the child
+ Child = os.popen(string.join(arguments," "),"w");
+ Child.write(PlainText);
+ if Child.close() != None:
+ raise Error, "Child gave a non-zero return code";
+
+except:
+ # Error Reply Header
+ Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
+ ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
+
+ # Error Body
+ Subst = {};
+ Subst["__ERROR__"] = ErrMsg;
+ Subst["__ADMIN__"] = ReplyTo;
+
+ Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
+ List = traceback.extract_tb(sys.exc_traceback);
+ if len(List) >= 1:
+ Trace = Trace + "Python Stack Trace:\n";
+ for x in List:
+ Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
+
+ Subst["__TRACE__"] = Trace;
+
+ # Try to send the bounce
+ try:
+ if ErrorTemplate != None:
+ ErrReply = TemplateSubst(Subst,open(ErrorTemplate,"r").read());
+ else:
+ ErrReply = "\n"+str(Subst)+"\n";
+
+ Child = os.popen("/usr/sbin/sendmail -t","w");
+ Child.write(ErrReplyHead);
+ Child.write(ErrReply);
+ if Child.close() != None:
+ raise Error, "Sendmail gave a non-zero return code";
+ except:
+ sys.exit(EX_TEMPFAIL);
+
+ if ErrType != EX_PERMFAIL:
+ sys.exit(ErrType);
+ sys.exit(0);
+
#!/usr/bin/env python
# -*- mode: python -*-
-import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, posix, getopt;
+import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, os, getopt;
import string, pwd
from userdir_gpg import *;
from userdir_ldap import *;
global l;
l = ldap.open(LDAPServer);
if Debug == None:
- F = open(PassDir+"/pass-"+pwd.getpwuid(posix.getuid())[0],"r");
+ F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
AccessPass = string.split(string.strip(F.readline())," ");
l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
F.close();
# -*- mode: python -*-
# Generates passwd, shadow and group files from the ldap directory.
-import string, re, time, ldap, getopt, sys, os, posix, pwd;
+import string, re, time, ldap, getopt, sys, os, pwd;
from userdir_ldap import *;
PasswdAttrs = None;
# Connect to the ldap server
l = ldap.open(LDAPServer);
-F = open(PassDir+"/pass-"+pwd.getpwuid(posix.getuid())[0],"r");
+F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
Pass = string.split(string.strip(F.readline())," ");
F.close();
l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
# in the directory but not in the key ring will be removed from the
# directory.
-import string, re, time, ldap, getopt, sys, pwd, posix;
+import string, re, time, ldap, getopt, sys, pwd, os;
from userdir_ldap import *;
from userdir_gpg import *;
UnknownMap[Split[0]] = string.strip(Split[1]);
# Process options
-AdminUser = pwd.getpwuid(posix.getuid())[0];
+AdminUser = pwd.getpwuid(os.getuid())[0];
(options, arguments) = getopt.getopt(sys.argv[1:], "au:m:n")
for (switch, val) in options:
if (switch == '-u'):
#!/usr/bin/env python
# -*- mode: python -*-
-import string, re, time, ldap, getopt, sys, pwd, posix;
+import string, re, time, ldap, getopt, sys, pwd, os;
from userdir_gpg import *;
Output = "extrakeys.gpg";
# Process options
-AdminUser = pwd.getpwuid(posix.getuid())[0];
+AdminUser = pwd.getpwuid(os.getuid())[0];
(options, arguments) = getopt.getopt(sys.argv[1:], "o:")
for (switch, val) in options:
if (switch == '-o'):
# -r Enable 'root' functions, do this if your uid has access to
# restricted variables.
-import string, time, posix, pwd, sys, getopt, ldap, crypt, whrandom, readline, copy;
+import string, time, os, pwd, sys, getopt, ldap, crypt, whrandom, readline, copy;
from userdir_ldap import *;
RootMode = 0;
print;
# Main program starts here
-User = pwd.getpwuid(posix.getuid())[0];
+User = pwd.getpwuid(os.getuid())[0];
BindUser = User;
# Process options
(options, arguments) = getopt.getopt(sys.argv[1:], "nu:c:a:r")
Count = Count + 1;
print "There are",Count,"developers as of",time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
+if arguments[0] == "echelon":
+ Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,\
+ "(&(|(activity-pgp=*)(activity-from=*))(&(keyfingerprint=*)(gidnumber=800)))",\
+ ["activity-pgp","activity-from"]);
+ Count = 0;
+ PGPCount = 0;
+ for x in Attrs:
+ Count = Count + 1;
+ if x[1].has_key("activity-pgp"):
+ PGPCount = PGPCount + 1;
+ print "Echelon has seen",Count,"developers, with",PGPCount,"PGP confirms as of",time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
+
if arguments[0] == "keystat":
Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=*",\
["keyfingerprint"]);
#!/usr/bin/env python
# -*- mode: python -*-
-import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, posix;
+import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, os;
import string, pwd
from userdir_gpg import *;
from userdir_ldap import *;
# Connect to the ldap server
l = ldap.open(LDAPServer);
- F = open(PassDir+"/pass-"+pwd.getpwuid(posix.getuid())[0],"r");
+ F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
AccessPass = string.split(string.strip(F.readline())," ");
F.close();
# Connect to the ldap server
l = ldap.open(LDAPServer);
- F = open(PassDir+"/pass-"+pwd.getpwuid(posix.getuid())[0],"r");
+ F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
AccessPass = string.split(string.strip(F.readline())," ");
F.close();
+ l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
+
+ # Check for a locked account
+ Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
+ if (string.find(GetAttr(Attrs[0],"userPassword"),"*LK*") != -1):
+ raise Error, "This account is locked";
# Modify the password
- l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
l.modify_s(Dn,Rec);
# Start of main program
# Drop messages from a mailer daemon.
-if posix.environ.has_key('SENDER') == 0 or len(posix.environ['SENDER']) == 0:
+if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
sys.exit(0);
ErrMsg = "Indeterminate Error";
# Send the message through sendmail
ErrMsg = "A problem occured while trying to send the reply";
- Child = posix.popen("/usr/sbin/sendmail -t","w");
-# Child = posix.popen("cat","w");
+ 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";
except:
# Error Reply Header
Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
- ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (posix.environ['SENDER'],ReplyTo,Date);
+ ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
# Error Body
Subst = {};
try:
ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
- Child = posix.popen("/usr/sbin/sendmail -t","w");
+ Child = os.popen("/usr/sbin/sendmail -t","w");
Child.write(ErrReplyHead);
Child.write(ErrReply);
if Child.close() != None:
trap "rm -f lock > /dev/null 2>&1" exit
rsync -e ssh -rp sshdist@samosa:/var/cache/userdir-ldap/hosts/$HOST . > /dev/null 2>&1
makedb $HOST/passwd.tdb -o passwd.db > /dev/null 2>&1
-makedb $HOST/shadow.tdb -o shadow.db > /dev/null 2>&1
+(umask 027 && makedb $HOST/shadow.tdb -o shadow.db) > /dev/null 2>&1
+chown root.shadow shadow.db
makedb $HOST/group.tdb -o group.db > /dev/null 2>&1
ln -sf $HOST/ssh-rsa-shadow . > /dev/null 2>&1
#!/usr/bin/env python
# -*- mode: python -*-
-import string, re, time, ldap, getopt, sys, posix, pwd;
+import string, re, time, ldap, getopt, sys, os, pwd;
from userdir_ldap import *;
from userdir_gpg import *;
# Initialize the substitution Map
Subst = {}
Subst["__REALNAME__"] = FullName;
-Subst["__WHOAMI__"] = pwd.getpwuid(posix.getuid())[0];
+Subst["__WHOAMI__"] = pwd.getpwuid(os.getuid())[0];
Subst["__DATE__"] = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
Subst["__LOGIN__"] = account;
Subst["__PRIVATE__"] = privsub;
Subst["__EMAIL__"] = email;
Subst["__PASSWORD__"] = CryptedPass;
-Subst["__LISTPASS__"] = string.strip(open(pwd.getpwuid(posix.getuid())[5]+"/.debian-lists_passwd","r").read());
+Subst["__LISTPASS__"] = string.strip(open(pwd.getpwuid(os.getuid())[5]+"/.debian-lists_passwd","r").read());
# Generate the LDAP request
Rec = [(ldap.MOD_REPLACE,"uid",account),
# Send the Welcome message
print "Sending Welcome Email"
Reply = TemplateSubst(Subst,open("templates/welcome-message-"+gidnumber,"r").read());
-Child = posix.popen("/usr/sbin/sendmail -t","w");
-#Child = posix.popen("cat","w");
+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";
# DGMS -> DD DDD + (MM + (SS.SSSSSS)/60)/60
# For Latitude + is North, for Longitude + is East
-import string, re, time, ldap, getopt, sys, pwd, posix;
+import string, re, time, ldap, getopt, sys, pwd, os;
from userdir_ldap import *;
Anon = 0;
GPGPath = "gpg"
GPGBasicOptions = ["--no-options","--batch","--load-extension","rsa",\
"--no-default-keyring","--always-trust"];
-GPGKeyRings = ["--keyring","/usr/share/keyrings/debian-keyring.pgp",\
- "--keyring","/usr/share/keyrings/debian-keyring.gpg"];
+GPGKeyRings = [];
GPGSigOptions = ["--output","-"];
GPGSearchOptions = ["--dry-run","--with-colons","--fingerprint"];
GPGEncryptOptions = ["--output","-","--quiet","--always-trust",\
AgeCutOff = 4*24*60*60;
FutureCutOff = 3*24*60*60;
+# Set the keyrings, the input is a list of keyrings
+def SetKeyrings(Rings):
+ for x in Rings:
+ GPGKeyRings.append("--keyring");
+ GPGKeyRings.append(x);
+
# GetClearSig takes an un-seekable email message stream (mimetools.Message)
# and returns a standard PGP '---BEGIN PGP SIGNED MESSAGE---' bounded
# clear signed text.
# Some routines and configuration that are used by the ldap progams
import termios, TERMIOS, re, string, imp, ldap, sys, whrandom, crypt, rfc822;
+import userdir_gpg
try:
File = open("/etc/userdir-ldap/userdir-ldap.conf");
Ech_ErrorLog = ConfModule.ech_errorlog;
Ech_MainLog = ConfModule.ech_mainlog;
+# Break up the keyring list
+userdir_gpg.SetKeyrings(string.split(ConfModule.keyrings,":"));
+
# This is a list of common last-name prefixes
LastNamesPre = {"van": None, "le": None, "de": None, "di": None};