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