First version of a check for ssh keys
[mirror/userdir-ldap.git] / ud-mailgate
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3
4 #   Prior copyright probably rmurray, troup, joey, jgg -- weasel 2008
5 #   Copyright (c) 2008 Peter Palfrader <peter@palfrader.org>
6 #   Copyright (c) 2008 Joerg Jaspert <joerg@debian.org>
7
8 import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, os, commands
9 import pwd, tmpfile
10 from userdir_gpg import *
11 from userdir_ldap import *
12
13 # Error codes from /usr/include/sysexits.h
14 ReplyTo = ConfModule.replyto;
15 PingFrom = ConfModule.pingfrom;
16 ChPassFrom = ConfModule.chpassfrom;
17 ChangeFrom = ConfModule.changefrom;
18 ReplayCacheFile = ConfModule.replaycachefile;
19 SSHFingerprintFile = ConfModule.fingerprintfile
20
21 EX_TEMPFAIL = 75;
22 EX_PERMFAIL = 65;      # EX_DATAERR
23 Error = 'Message Error';
24 SeenKey = 0;
25 SeenDNS = 0;
26 mailRBL = {}
27 mailRHSBL = {}
28 mailWhitelist = {}
29 SeenList = {}
30 DNS = {}
31
32 SSHFingerprint = re.compile('^(\d+) ([0-9a-f\:]{47}) (.+)$')
33
34 ArbChanges = {"c": "..",
35               "l": ".*",
36               "facsimileTelephoneNumber": ".*",
37               "telephoneNumber": ".*",
38               "postalAddress": ".*",
39               "postalCode": ".*",
40               "loginShell": ".*",
41               "emailForward": "^([^<>@]+@.+)?$",
42               "jabberJID": "^([^<>@]+@.+)?$",
43               "ircNick": ".*",
44               "icqUin": "^[0-9]*$",
45               "onVacation": ".*",
46               "labeledURI": ".*",
47               "birthDate": "^([0-9]{4})([01][0-9])([0-3][0-9])$",
48               "mailDisableMessage": ".*",
49               "mailGreylisting": "^(TRUE|FALSE)$",
50               "mailCallout": "^(TRUE|FALSE)$",
51               "VoIP": ".*",
52 };
53
54 DelItems = {"c": None,
55             "l": None,
56             "facsimileTelephoneNumber": None,
57             "telephoneNumber": None,
58             "postalAddress": None,
59             "postalCode": None,
60             "emailForward": None,
61             "ircNick": None,
62             "onVacation": None,
63             "labeledURI": None,
64             "latitude": None,
65             "longitude": None,
66             "icqUin": None,
67             "jabberJID": None,
68             "jpegPhoto": None,
69             "dnsZoneEntry": None,
70             "sshRSAAuthKey": None,
71             "sshDSAAuthKey": None,
72             "birthDate" : None,
73             "mailGreylisting": None,
74             "mailCallout": None,
75             "mailRBL": None,
76             "mailRHSBL": None,
77             "mailWhitelist": None,
78             "mailDisableMessage": None,
79             "VoIP": None,
80             };
81
82 # Decode a GPS location from some common forms
83 def LocDecode(Str,Dir):
84    # Check for Decimal degrees, DGM, or DGMS
85    if re.match("^[+-]?[\d.]+$",Str) != None:
86       return Str;
87
88    Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
89    
90    # Check for DDDxMM.MMMM where x = [nsew]
91    Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
92    if Match != None:
93       G = Match.groups();
94       Deg = G[0]; Min = G[2]; Dr = G[1];
95
96    # Check for DD.DD x 
97    Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
98    if Match != None:
99       G = Match.groups();
100       Deg = G[0]; Dr = G[1];
101
102    # Check for DD:MM.MM x 
103    Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
104    if Match != None:
105       G = Match.groups();
106       Deg = G[0]; Min = G[1]; Dr = G[2];
107
108    # Check for DD:MM:SS.SS x
109    Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
110    if Match != None:
111       G = Match.groups();
112       Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
113       
114    # Some simple checks
115    if float(Deg) > 180:
116       raise "Failed","Bad degrees";
117    if Min != None and float(Min) > 60:
118       raise "Failed","Bad minutes";
119    if Sec != None and float(Sec) > 60:
120       raise "Failed","Bad seconds";
121       
122    # Pad on an extra leading 0 to disambiguate small numbers
123    if len(Deg) <= 1 or Deg[1] == '.':
124       Deg = '0' + Deg;
125    if Min != None and (len(Min) <= 1 or Min[1] == '.'):
126       Min = '0' + Min;
127    if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
128       Sec = '0' + Sec;
129    
130    # Construct a DGM/DGMS type value from the components.
131    Res = "+"
132    if Dr == Dir[1]:
133       Res = "-";
134    Res = Res + Deg;
135    if Min != None:
136       Res = Res + Min;
137    if Sec != None:
138       Res = Res + Sec;
139    return Res;
140               
141 # Handle changing a set of arbitary fields
142 #  <field>: value
143 def DoArbChange(Str,Attrs):
144    Match = re.match("^([^ :]+): (.*)$",Str);
145    if Match == None:
146       return None;
147    G = Match.groups();
148
149    attrName = G[0].lower();
150    for i in ArbChanges.keys():
151       if i.lower() == attrName:
152          attrName = i;
153          break;
154    if ArbChanges.has_key(attrName) == 0:
155       return None;
156
157    if re.match(ArbChanges[attrName],G[1]) == None:
158       raise Error, "Item does not match the required format"+ArbChanges[attrName];
159
160 #   if attrName == 'birthDate':
161 #      (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
162 #    $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
163 #    if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
164 #      if ($bd_mo == 2) {
165 #        if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
166 #          $bd_ok = 1;
167 #        } elsif ($bd_day <= 28) {
168 #          $bd_ok = 1;
169 #        }
170 #      } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
171 #       if ($bd_day <= 30) {
172 #         $bd_ok = 1;
173 #       }
174 #      } else {
175 #       if ($bd_day <= 31) {
176 #         $bd_ok = 1;
177 #       }
178 #      }
179 #    }
180 #  } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
181 #    $bd_ok = 1;
182 #  }
183    Attrs.append((ldap.MOD_REPLACE,attrName,G[1]));
184    return "Changed entry %s to %s"%(attrName,G[1]);
185
186 # Handle changing a set of arbitary fields
187 #  <field>: value
188 def DoDel(Str,Attrs):
189    Match = re.match("^del (.*)$",Str);
190    if Match == None:
191       return None;
192    G = Match.groups();
193
194    attrName = G[0].lower();
195    for i in DelItems.keys():
196       if i.lower() == attrName:
197          attrName = i;
198          break;
199    if DelItems.has_key(attrName) == 0:
200       return "Cannot erase entry %s"%(attrName);
201
202    Attrs.append((ldap.MOD_DELETE,attrName,None));
203    return "Removed entry %s"%(attrName);
204
205 # Handle a position change message, the line format is:
206 #  Lat: -12412.23 Long: +12341.2342
207 def DoPosition(Str,Attrs):
208    Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
209    if Match == None:
210       return None;
211
212    G = Match.groups();
213    try:
214       sLat = LocDecode(G[0],"ns");
215       sLong = LocDecode(G[1],"ew");
216       Lat = DecDegree(sLat,1);
217       Long = DecDegree(sLong,1);
218    except:
219       raise Error, "Positions were found, but they are not correctly formed";
220
221    Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
222    Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
223    return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
224
225 # Load bad ssh fingerprints
226 def LoadBadSSH():
227    f = open(SSHFingerprintFile, "r")
228    bad = []
229    FingerprintLine = re.compile('^([0-9a-f\:]{47}).*$')
230    for line in f.readlines():
231       Match = FingerprintLine.match(line)
232       if Match is not None:
233          g = Match.groups()
234          bad.append(g[0])
235    return bad
236
237 # Handle an SSH authentication key, the line format is:
238 #  [options] 1024 35 13188913666680[..] [comment]
239 def DoSSH(Str,Attrs, badkeys):
240    Match = SSH2AuthSplit.match(Str);
241    if Match == None:
242       Match = re.compile('^1024 (\d+) ').match(Str)
243       if Match is not None:
244          return "SSH1 keys not supported anymore"
245       return None;
246
247    (fd, path) = tempfile.mkstemp("", "sshkeytry")
248    f = open(path, "w")
249    f.write(Str)
250    f.close
251    (result, output) = commands.getstatusoutput("ssh-keygen -f %s -l" % (path))
252    os.remove(path)
253    if (result != 0):
254       sys.stderr.write("ssh-keygen -l invocation failed!\n%s\n" % (output))
255       sys.exit(result)
256
257    Match = SSHFingerprint.match(output)
258
259    g = Match.groups()
260    if (g[0] < 1024):
261       return "SSH keys must have at least 1024 bits, not added"
262    elif g[0] in badkeys:
263       return "Submitted SSH Key known to be bad and insecure, not added"
264
265    global SeenKey;
266    if SeenKey:
267      Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
268      return "SSH Key added "+FormatSSHAuth(Str);
269       
270    Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
271    SeenKey = 1;
272    return "SSH Keys replaced with "+FormatSSHAuth(Str);
273
274 # Handle changing a dns entry
275 #  host IN A     12.12.12.12
276 #  host IN AAAA  1234::5678
277 #  host IN CNAME foo.bar.    <- Trailing dot is required
278 #  host IN MX    foo.bar.    <- Trailing dot is required
279 def DoDNS(Str,Attrs,DnRecord):
280    cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
281    arecord     = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
282    mxrecord    = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
283    #aaaarecord  = re.match('^[-\w]+\s+IN\s+AAAA\s+((?:[0-9a-f]{1,4})(?::[0-9a-f]{1,4})*(?::(?:(?::[0-9a-f]{1,4})*|:))?)$',Str,re.IGNORECASE)
284    aaaarecord  = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
285
286    if cnamerecord == None and\
287       arecord == None and\
288       mxrecord == None and\
289       aaaarecord == None:
290      return None;
291
292    # Check if the name is already taken
293    G = re.match('^([-\w+]+)\s',Str)
294    if G == None:
295      raise Error, "Hostname not found although we already passed record syntax checks"
296    hostname = G.group(1)
297
298    # Check for collisions
299    global l;
300    # [JT 20070409 - search for both tab and space suffixed hostnames
301    #  since we accept either.  It'd probably be better to parse the
302    #  incoming string in order to construct what we feed LDAP rather
303    #  than just passing it through as is.]
304    filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
305    Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
306    for x in Rec:
307       if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
308          return "DNS entry is already owned by " + GetAttr(x,"uid")
309
310    global SeenDNS;
311    global DNS;
312
313    if cnamerecord:
314      if DNS.has_key(hostname):
315        return "CNAME and other RR types not allowed: "+Str
316      else:
317        DNS[hostname] = 2
318    else:
319      if DNS.has_key(hostname) and DNS[hostname] == 2:
320        return "CNAME and other RR types not allowed: "+Str
321      else:
322        DNS[hostname] = 1
323
324    if cnamerecord != None:
325      sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
326    elif arecord != None:
327      ipaddress = arecord.group(1)
328      for quad in ipaddress.split('.'):
329        if not (int(quad) >=0 and int(quad) <= 255):
330          return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
331      sanitized = "%s IN A %s"% (hostname, ipaddress)
332    elif mxrecord != None:
333      priority = mxrecord.group(1)
334      mx = mxrecord.group(2)
335      sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
336    elif aaaarecord != None:
337      ipv6address = aaaarecord.group(1)
338      parts = ipv6address.split(':')
339      if len(parts) > 8:
340        return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
341      if len(parts) <= 2:
342        return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
343      if parts[0] == "":
344        parts.pop(0)
345      if parts[-1] == "":
346        parts.pop(-1)
347      seenEmptypart = False
348      for p in parts:
349        if len(p) > 4:
350          return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
351        if p == "":
352          if seenEmptypart:
353            return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
354          seenEmptypart = True
355      sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
356    else:
357      raise Error, "None of the types I recognize was it.  I shouldn't be here.  confused."
358
359    if SeenDNS:
360      Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
361      return "DNS Entry added "+sanitized;
362
363    Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
364    SeenDNS = 1;
365    return "DNS Entry replaced with "+sanitized;
366
367 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
368 def DoRBL(Str,Attrs):
369    Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
370    if Match == None:
371       return None
372    
373    if Match.group(1) == "rbl":
374       Key = "mailRBL"
375    if Match.group(1) == "rhsbl":
376       Key = "mailRHSBL"
377    if Match.group(1) == "whitelist":
378       Key = "mailWhitelist"
379    Host = Match.group(2)
380
381    global SeenList
382    if SeenList.has_key(Key):
383      Attrs.append((ldap.MOD_ADD,Key,Host))
384      return "%s added %s" % (Key,Host)
385       
386    Attrs.append((ldap.MOD_REPLACE,Key,Host))
387    SeenList[Key] = 1;
388    return "%s replaced with %s" % (Key,Host)
389
390 # Handle an [almost] arbitary change
391 def HandleChange(Reply,DnRecord,Key):
392    global PlainText;
393    Lines = re.split("\n *\r?",PlainText);
394
395    Result = "";
396    Attrs = [];
397    Show = 0;
398    for Line in Lines: 
399       Line = Line.strip()
400       if Line == "":
401          continue;
402
403       # Try to process a command line
404       Result = Result + "> "+Line+"\n";
405       try:
406          if Line == "show":
407            Show = 1;
408            Res = "OK";
409          else:
410             badkeys = LoadBadSSH()
411             Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
412                   DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys) or \
413                   DoDel(Line,Attrs) or DoRBL(Line,Attrs)
414       except:
415          Res = None;
416          Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
417          
418       # Fail, if someone tries to send someone elses signed email to the
419       # daemon then we want to abort ASAP.
420       if Res == None:
421          Result = Result + "Command is not understood. Halted\n";
422          break;
423       Result = Result + Res + "\n";
424
425    # Connect to the ldap server
426    l = ldap.open(LDAPServer);
427    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
428    AccessPass = F.readline().strip().split(" ")
429    F.close();
430
431    # Modify the record
432    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
433    oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
434    if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1) 
435        or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
436       raise Error, "This account is locked";
437    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
438    l.modify_s(Dn,Attrs);
439
440    Attribs = "";
441    if Show == 1:
442       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
443       if len(Attrs) == 0:
444          raise Error, "User not found"
445       Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
446       
447    Subst = {};
448    Subst["__FROM__"] = ChangeFrom;
449    Subst["__EMAIL__"] = EmailAddress(DnRecord);
450    Subst["__ADMIN__"] = ReplyTo;
451    Subst["__RESULT__"] = Result;
452    Subst["__ATTR__"] = Attribs;
453
454    return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
455    
456 # Handle ping handles an email sent to the 'ping' address (ie this program
457 # called with a ping argument) It replies with a dump of the public records.
458 def HandlePing(Reply,DnRecord,Key):
459    Subst = {};
460    Subst["__FROM__"] = PingFrom;
461    Subst["__EMAIL__"] = EmailAddress(DnRecord);
462    Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
463    Subst["__ADMIN__"] = ReplyTo;
464
465    return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
466
467 # Handle a change password email sent to the change password address
468 # (this program called with the chpass argument)
469 def HandleChPass(Reply,DnRecord,Key):
470    # Generate a random password
471    Password = GenPass();
472    Pass = HashPass(Password);
473       
474    # Use GPG to encrypt it      
475    Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
476                         "0x"+Key[1],Key[4]);
477    Password = None;
478
479    if Message == None:
480       raise Error, "Unable to generate the encrypted reply, gpg failed.";
481
482    if (Key[4] == 1):
483       Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
484    else:
485       Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
486              "mode, without IDEA. This message cannot be decoded using PGP 2.x";
487    
488    Subst = {};
489    Subst["__FROM__"] = ChPassFrom;
490    Subst["__EMAIL__"] = EmailAddress(DnRecord);
491    Subst["__CRYPTTYPE__"] = Type;
492    Subst["__PASSWORD__"] = Message;
493    Subst["__ADMIN__"] = ReplyTo;
494    Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
495    
496    # Connect to the ldap server
497    l = ldap.open(LDAPServer);
498    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
499    AccessPass = F.readline().strip().split(" ")
500    F.close();
501    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
502
503    # Check for a locked account
504    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
505    if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
506              or GetAttr(Attrs[0],"userPassword").startswith("!"):
507       raise Error, "This account is locked";
508
509    # Modify the password
510    Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
511    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
512    l.modify_s(Dn,Rec);
513
514    return Reply;
515       
516 # Start of main program
517
518 # Drop messages from a mailer daemon.
519 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
520    sys.exit(0);
521
522 ErrMsg = "Indeterminate Error";
523 ErrType = EX_TEMPFAIL;
524 try:
525    # Startup the replay cache
526    ErrType = EX_TEMPFAIL;
527    ErrMsg = "Failed to initialize the replay cache:";
528    RC = ReplayCache(ReplayCacheFile);
529    RC.Clean();
530
531    # Get the email 
532    ErrType = EX_PERMFAIL;
533    ErrMsg = "Failed to understand the email or find a signature:";
534    Email = mimetools.Message(sys.stdin,0);
535    Msg = GetClearSig(Email);
536
537    ErrMsg = "Message is not PGP signed:"
538    if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
539       Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
540       raise Error, "No PGP signature";
541    
542    # Check the signature
543    ErrMsg = "Unable to check the signature or the signature was invalid:";
544    Res = GPGCheckSig(Msg[0]);
545
546    if Res[0] != None:
547       raise Error, Res[0];
548       
549    if Res[3] == None:
550       raise Error, "Null signature text";
551
552    # Extract the plain message text in the event of mime encoding
553    global PlainText;
554    ErrMsg = "Problem stripping MIME headers from the decoded message"
555    if Msg[1] == 1:
556       try:
557          Index = Res[3].index("\n\n") + 2;
558       except ValueError:
559          Index = Res[3].index("\n\r\n") + 3;
560       PlainText = Res[3][Index:];
561    else:
562       PlainText = Res[3];   
563
564    # Check the signature against the replay cache
565    ErrMsg = "The replay cache rejected your message. Check your clock!";
566    Rply = RC.Check(Res[1]);
567    if Rply != None:
568       raise Error, Rply;
569
570    # Connect to the ldap server
571    ErrType = EX_TEMPFAIL;
572    ErrMsg = "An error occured while performing the LDAP lookup";
573    global l;
574    l = ldap.open(LDAPServer);
575    l.simple_bind_s("","");
576
577    # Search for the matching key fingerprint
578    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
579
580    ErrType = EX_PERMFAIL;
581    if len(Attrs) == 0:
582       raise Error, "Key not found"
583    if len(Attrs) != 1:
584       raise Error, "Oddly your key fingerprint is assigned to more than one account.."
585
586    RC.Add(Res[1]);
587
588    # Determine the sender address
589    ErrMsg = "A problem occured while trying to formulate the reply";
590    Sender = Email.getheader("Reply-To");
591    if Sender == None:
592       Sender = Email.getheader("From");
593    if Sender == None:
594       raise Error, "Unable to determine the sender's address";
595
596    # Formulate a reply
597    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
598    Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
599
600    # Dispatch
601    if sys.argv[1] == "ping":
602       Reply = HandlePing(Reply,Attrs[0],Res[2]);
603    elif sys.argv[1] == "chpass":
604       if PlainText.strip().find("Please change my Debian password") != 0:
605          raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
606       Reply = HandleChPass(Reply,Attrs[0],Res[2]);
607    elif sys.argv[1] == "change":
608       Reply = HandleChange(Reply,Attrs[0],Res[2]);
609    else:
610       print sys.argv;
611       raise Error, "Incorrect Invokation";
612
613    # Send the message through sendmail      
614    ErrMsg = "A problem occured while trying to send the reply";
615    Child = os.popen("/usr/sbin/sendmail -t","w");
616 #   Child = os.popen("cat","w");
617    Child.write(Reply);
618    if Child.close() != None:
619       raise Error, "Sendmail gave a non-zero return code";
620
621 except:
622    # Error Reply Header
623    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
624    ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
625
626    # Error Body
627    Subst = {};
628    Subst["__ERROR__"] = ErrMsg;
629    Subst["__ADMIN__"] = ReplyTo;
630
631    Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
632    List = traceback.extract_tb(sys.exc_traceback);
633    if len(List) > 1:
634       Trace = Trace + "Python Stack Trace:\n";
635       for x in List:
636          Trace = Trace +  "   %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
637
638    Subst["__TRACE__"] = Trace;
639
640    # Try to send the bounce
641    try:
642       ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
643
644       Child = os.popen("/usr/sbin/sendmail -t","w");
645       Child.write(ErrReplyHead);
646       Child.write(ErrReply);
647       if Child.close() != None:
648          raise Error, "Sendmail gave a non-zero return code";
649    except:
650       sys.exit(EX_TEMPFAIL);
651       
652    if ErrType != EX_PERMFAIL:
653       sys.exit(ErrType);
654    sys.exit(0);
655