Merge sshkeys check with the alioth userdir-ldap-common
[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               "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, uid):
240    Match = SSH2AuthSplit.match(Str);
241    g = Match.groups()
242    typekey = g[1]
243    if Match == None:
244       Match = re.compile('^1024 (\d+) ').match(Str)
245       if Match is not None:
246          return "SSH1 keys not supported anymore"
247       return None;
248
249    (fd, path) = tempfile.mkstemp(".pub", "sshkeytry", "/tmp")
250    f = open(path, "w")
251    f.write("%s\n" % (Str))
252    f.close()
253    cmd = "/usr/bin/ssh-keygen -l -f %s < /dev/null" % (path)
254    (result, output) = commands.getstatusoutput(cmd)
255    os.remove(path)
256    if (result != 0):
257       raise Error, "ssh-keygen -l invocation failed!\n%s\n" % (output)
258
259
260    # Head
261    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
262    ErrReplyHead = "From: %s\nCc: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],os.environ['SENDER'],ReplyTo,Date)
263    Subst = {}
264    Subst["__ADMIN__"] = ReplyTo
265    Subst["__USER__"] = uid
266
267    Match = SSHFingerprint.match(output)
268    g = Match.groups()
269
270    if int(g[0]) < 1024:
271       try:
272          # Body
273          Subst["__ERROR__"] = "SSH keysize %s is below limit 1024" % (g[0])
274          ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
275
276          Child = os.popen("/usr/sbin/sendmail -t","w")
277          Child.write(ErrReplyHead)
278          Child.write(ErrReply)
279          if Child.close() != None:
280             raise Error, "Sendmail gave a non-zero return code"
281       except:
282          sys.exit(EX_TEMPFAIL)
283
284       # And now break and stop processing input, which sends a reply to the user.
285       raise Error, "SSH keys must have at least 1024 bits, processing halted, NOTHING MODIFIED AT ALL"
286    elif g[1] in badkeys:
287       try:
288          # Body
289          Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
290          ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
291
292          Child = os.popen("/usr/sbin/sendmail -t","w")
293          Child.write(ErrReplyHead)
294          Child.write(ErrReply)
295          if Child.close() != None:
296             raise Error, "Sendmail gave a non-zero return code"
297       except:
298          sys.exit(EX_TEMPFAIL)
299
300       # And now break and stop processing input, which sends a reply to the user.
301       raise Error, "Submitted SSH Key known to be bad and insecure, processing halted, NOTHING MODIFIED AT ALL"
302
303    if (typekey == "dss"):
304       return "DSA keys not accepted anymore"
305
306    global SeenKey;
307    if SeenKey:
308      Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
309      return "SSH Key added "+FormatSSHAuth(Str);
310       
311    Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
312    SeenKey = 1;
313    return "SSH Keys replaced with "+FormatSSHAuth(Str);
314
315 # Handle changing a dns entry
316 #  host IN A     12.12.12.12
317 #  host IN AAAA  1234::5678
318 #  host IN CNAME foo.bar.    <- Trailing dot is required
319 #  host IN MX    foo.bar.    <- Trailing dot is required
320 def DoDNS(Str,Attrs,DnRecord):
321    cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
322    arecord     = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
323    mxrecord    = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
324    #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)
325    aaaarecord  = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
326
327    if cnamerecord == None and\
328       arecord == None and\
329       mxrecord == None and\
330       aaaarecord == None:
331      return None;
332
333    # Check if the name is already taken
334    G = re.match('^([-\w+]+)\s',Str)
335    if G == None:
336      raise Error, "Hostname not found although we already passed record syntax checks"
337    hostname = G.group(1)
338
339    # Check for collisions
340    global l;
341    # [JT 20070409 - search for both tab and space suffixed hostnames
342    #  since we accept either.  It'd probably be better to parse the
343    #  incoming string in order to construct what we feed LDAP rather
344    #  than just passing it through as is.]
345    filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
346    Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
347    for x in Rec:
348       if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
349          return "DNS entry is already owned by " + GetAttr(x,"uid")
350
351    global SeenDNS;
352    global DNS;
353
354    if cnamerecord:
355      if DNS.has_key(hostname):
356        return "CNAME and other RR types not allowed: "+Str
357      else:
358        DNS[hostname] = 2
359    else:
360      if DNS.has_key(hostname) and DNS[hostname] == 2:
361        return "CNAME and other RR types not allowed: "+Str
362      else:
363        DNS[hostname] = 1
364
365    if cnamerecord != None:
366      sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
367    elif arecord != None:
368      ipaddress = arecord.group(1)
369      for quad in ipaddress.split('.'):
370        if not (int(quad) >=0 and int(quad) <= 255):
371          return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
372      sanitized = "%s IN A %s"% (hostname, ipaddress)
373    elif mxrecord != None:
374      priority = mxrecord.group(1)
375      mx = mxrecord.group(2)
376      sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
377    elif aaaarecord != None:
378      ipv6address = aaaarecord.group(1)
379      parts = ipv6address.split(':')
380      if len(parts) > 8:
381        return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
382      if len(parts) <= 2:
383        return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
384      if parts[0] == "":
385        parts.pop(0)
386      if parts[-1] == "":
387        parts.pop(-1)
388      seenEmptypart = False
389      for p in parts:
390        if len(p) > 4:
391          return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
392        if p == "":
393          if seenEmptypart:
394            return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
395          seenEmptypart = True
396      sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
397    else:
398      raise Error, "None of the types I recognize was it.  I shouldn't be here.  confused."
399
400    if SeenDNS:
401      Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
402      return "DNS Entry added "+sanitized;
403
404    Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
405    SeenDNS = 1;
406    return "DNS Entry replaced with "+sanitized;
407
408 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
409 def DoRBL(Str,Attrs):
410    Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
411    if Match == None:
412       return None
413    
414    if Match.group(1) == "rbl":
415       Key = "mailRBL"
416    if Match.group(1) == "rhsbl":
417       Key = "mailRHSBL"
418    if Match.group(1) == "whitelist":
419       Key = "mailWhitelist"
420    Host = Match.group(2)
421
422    global SeenList
423    if SeenList.has_key(Key):
424      Attrs.append((ldap.MOD_ADD,Key,Host))
425      return "%s added %s" % (Key,Host)
426       
427    Attrs.append((ldap.MOD_REPLACE,Key,Host))
428    SeenList[Key] = 1;
429    return "%s replaced with %s" % (Key,Host)
430
431 # Handle an [almost] arbitary change
432 def HandleChange(Reply,DnRecord,Key):
433    global PlainText;
434    Lines = re.split("\n *\r?",PlainText);
435
436    Result = "";
437    Attrs = [];
438    Show = 0;
439    for Line in Lines: 
440       Line = Line.strip()
441       if Line == "":
442          continue;
443
444       # Try to process a command line
445       Result = Result + "> "+Line+"\n";
446       try:
447          if Line == "show":
448             Show = 1;
449             Res = "OK";
450          else:
451             badkeys = LoadBadSSH()
452             Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
453                   DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
454                   DoDel(Line,Attrs) or DoRBL(Line,Attrs)
455       except:
456          Res = None;
457          Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
458          
459       # Fail, if someone tries to send someone elses signed email to the
460       # daemon then we want to abort ASAP.
461       if Res == None:
462          Result = Result + "Command is not understood. Halted\n";
463          break;
464       Result = Result + Res + "\n";
465
466    # Connect to the ldap server
467    l = ldap.open(LDAPServer);
468    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
469    AccessPass = F.readline().strip().split(" ")
470    F.close();
471
472    # Modify the record
473    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
474    oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
475    if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1) 
476        or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
477       raise Error, "This account is locked";
478    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
479    l.modify_s(Dn,Attrs);
480
481    Attribs = "";
482    if Show == 1:
483       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
484       if len(Attrs) == 0:
485          raise Error, "User not found"
486       Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
487       
488    Subst = {};
489    Subst["__FROM__"] = ChangeFrom;
490    Subst["__EMAIL__"] = EmailAddress(DnRecord);
491    Subst["__ADMIN__"] = ReplyTo;
492    Subst["__RESULT__"] = Result;
493    Subst["__ATTR__"] = Attribs;
494
495    return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
496    
497 # Handle ping handles an email sent to the 'ping' address (ie this program
498 # called with a ping argument) It replies with a dump of the public records.
499 def HandlePing(Reply,DnRecord,Key):
500    Subst = {};
501    Subst["__FROM__"] = PingFrom;
502    Subst["__EMAIL__"] = EmailAddress(DnRecord);
503    Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
504    Subst["__ADMIN__"] = ReplyTo;
505
506    return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
507
508 # Handle a change password email sent to the change password address
509 # (this program called with the chpass argument)
510 def HandleChPass(Reply,DnRecord,Key):
511    # Generate a random password
512    Password = GenPass();
513    Pass = HashPass(Password);
514       
515    # Use GPG to encrypt it      
516    Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
517                         "0x"+Key[1],Key[4]);
518    Password = None;
519
520    if Message == None:
521       raise Error, "Unable to generate the encrypted reply, gpg failed.";
522
523    if (Key[4] == 1):
524       Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
525    else:
526       Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
527              "mode, without IDEA. This message cannot be decoded using PGP 2.x";
528    
529    Subst = {};
530    Subst["__FROM__"] = ChPassFrom;
531    Subst["__EMAIL__"] = EmailAddress(DnRecord);
532    Subst["__CRYPTTYPE__"] = Type;
533    Subst["__PASSWORD__"] = Message;
534    Subst["__ADMIN__"] = ReplyTo;
535    Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
536    
537    # Connect to the ldap server
538    l = ldap.open(LDAPServer);
539    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
540    AccessPass = F.readline().strip().split(" ")
541    F.close();
542    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
543
544    # Check for a locked account
545    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
546    if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
547              or GetAttr(Attrs[0],"userPassword").startswith("!"):
548       raise Error, "This account is locked";
549
550    # Modify the password
551    Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
552    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
553    l.modify_s(Dn,Rec);
554
555    return Reply;
556       
557 # Start of main program
558
559 # Drop messages from a mailer daemon.
560 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
561    sys.exit(0);
562
563 ErrMsg = "Indeterminate Error";
564 ErrType = EX_TEMPFAIL;
565 try:
566    # Startup the replay cache
567    ErrType = EX_TEMPFAIL;
568    ErrMsg = "Failed to initialize the replay cache:";
569    RC = ReplayCache(ReplayCacheFile);
570    RC.Clean();
571
572    # Get the email 
573    ErrType = EX_PERMFAIL;
574    ErrMsg = "Failed to understand the email or find a signature:";
575    Email = mimetools.Message(sys.stdin,0);
576    Msg = GetClearSig(Email);
577
578    ErrMsg = "Message is not PGP signed:"
579    if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
580       Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
581       raise Error, "No PGP signature";
582    
583    # Check the signature
584    ErrMsg = "Unable to check the signature or the signature was invalid:";
585    Res = GPGCheckSig(Msg[0]);
586
587    if Res[0] != None:
588       raise Error, Res[0];
589       
590    if Res[3] == None:
591       raise Error, "Null signature text";
592
593    # Extract the plain message text in the event of mime encoding
594    global PlainText;
595    ErrMsg = "Problem stripping MIME headers from the decoded message"
596    if Msg[1] == 1:
597       try:
598          Index = Res[3].index("\n\n") + 2;
599       except ValueError:
600          Index = Res[3].index("\n\r\n") + 3;
601       PlainText = Res[3][Index:];
602    else:
603       PlainText = Res[3];   
604
605    # Check the signature against the replay cache
606    ErrMsg = "The replay cache rejected your message. Check your clock!";
607    Rply = RC.Check(Res[1]);
608    if Rply != None:
609       raise Error, Rply;
610
611    # Connect to the ldap server
612    ErrType = EX_TEMPFAIL;
613    ErrMsg = "An error occured while performing the LDAP lookup";
614    global l;
615    l = ldap.open(LDAPServer);
616    l.simple_bind_s("","");
617
618    # Search for the matching key fingerprint
619    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
620
621    ErrType = EX_PERMFAIL;
622    if len(Attrs) == 0:
623       raise Error, "Key not found"
624    if len(Attrs) != 1:
625       raise Error, "Oddly your key fingerprint is assigned to more than one account.."
626
627    RC.Add(Res[1]);
628
629    # Determine the sender address
630    ErrMsg = "A problem occured while trying to formulate the reply";
631    Sender = Email.getheader("Reply-To");
632    if Sender == None:
633       Sender = Email.getheader("From");
634    if Sender == None:
635       raise Error, "Unable to determine the sender's address";
636
637    # Formulate a reply
638    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
639    Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
640
641    # Dispatch
642    if sys.argv[1] == "ping":
643       Reply = HandlePing(Reply,Attrs[0],Res[2]);
644    elif sys.argv[1] == "chpass":
645       if PlainText.strip().find("Please change my Debian password") != 0:
646          raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
647       Reply = HandleChPass(Reply,Attrs[0],Res[2]);
648    elif sys.argv[1] == "change":
649       Reply = HandleChange(Reply,Attrs[0],Res[2]);
650    else:
651       print sys.argv;
652       raise Error, "Incorrect Invokation";
653
654    # Send the message through sendmail      
655    ErrMsg = "A problem occured while trying to send the reply";
656    Child = os.popen("/usr/sbin/sendmail -t","w");
657 #   Child = os.popen("cat","w");
658    Child.write(Reply);
659    if Child.close() != None:
660       raise Error, "Sendmail gave a non-zero return code";
661
662 except:
663    # Error Reply Header
664    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
665    ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
666
667    # Error Body
668    Subst = {};
669    Subst["__ERROR__"] = ErrMsg;
670    Subst["__ADMIN__"] = ReplyTo;
671
672    Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
673    List = traceback.extract_tb(sys.exc_traceback);
674    if len(List) > 1:
675       Trace = Trace + "Python Stack Trace:\n";
676       for x in List:
677          Trace = Trace +  "   %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
678
679    Subst["__TRACE__"] = Trace;
680
681    # Try to send the bounce
682    try:
683       ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
684
685       Child = os.popen("/usr/sbin/sendmail -t","w");
686       Child.write(ErrReplyHead);
687       Child.write(ErrReply);
688       if Child.close() != None:
689          raise Error, "Sendmail gave a non-zero return code";
690    except:
691       sys.exit(EX_TEMPFAIL);
692       
693    if ErrType != EX_PERMFAIL:
694       sys.exit(ErrType);
695    sys.exit(0);
696