Notify users about unsupported SSH1 keys
[mirror/userdir-ldap.git] / ud-mailgate
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3 import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, os;
4 import string, pwd
5 from userdir_gpg import *;
6 from userdir_ldap import *;
7
8 # Error codes from /usr/include/sysexits.h
9 ReplyTo = ConfModule.replyto;
10 PingFrom = ConfModule.pingfrom;
11 ChPassFrom = ConfModule.chpassfrom;
12 ChangeFrom = ConfModule.changefrom;
13 ReplayCacheFile = ConfModule.replaycachefile;
14
15 EX_TEMPFAIL = 75;
16 EX_PERMFAIL = 65;      # EX_DATAERR
17 Error = 'Message Error';
18 SeenKey = 0;
19 SeenDNS = 0;
20 DNS = {}
21
22 ArbChanges = {"c": "..",
23               "l": ".*",
24               "facsimileTelephoneNumber": ".*",
25               "telephoneNumber": ".*",
26               "postalAddress": ".*",
27               "postalCode": ".*",
28               "loginShell": ".*",
29               "emailForward": "^([^<>@]+@.+)?$",
30               "ircNick": ".*",
31               "icqUin": "^[0-9]*$",
32               "onVacation": ".*",
33               "labeledURI": ".*"};
34
35 DelItems = {"c": None,
36             "l": None,
37             "facsimileTelephoneNumber": None,
38             "telephoneNumber": None,
39             "postalAddress": None,
40             "postalCode": None,
41             "emailForward": None,
42             "ircNick": None,
43             "onVacation": None,
44             "labeledURI": None,
45             "latitude": None,
46             "longitude": None,
47             "icqUin": None,
48             "dnsZoneEntry": None,
49             "sshRSAAuthKey": None,
50             "sshDSAAuthKey": None};
51
52 # Decode a GPS location from some common forms
53 def LocDecode(Str,Dir):
54    # Check for Decimal degrees, DGM, or DGMS
55    if re.match("^[+-]?[\d.]+$",Str) != None:
56       return Str;
57
58    Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
59    
60    # Check for DDDxMM.MMMM where x = [nsew]
61    Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
62    if Match != None:
63       G = Match.groups();
64       Deg = G[0]; Min = G[2]; Dr = G[1];
65
66    # Check for DD.DD x 
67    Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
68    if Match != None:
69       G = Match.groups();
70       Deg = G[0]; Dr = G[1];
71
72    # Check for DD:MM.MM x 
73    Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
74    if Match != None:
75       G = Match.groups();
76       Deg = G[0]; Min = G[1]; Dr = G[2];
77
78    # Check for DD:MM:SS.SS x
79    Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
80    if Match != None:
81       G = Match.groups();
82       Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
83       
84    # Some simple checks
85    if float(Deg) > 180:
86       raise "Failed","Bad degrees";
87    if Min != None and float(Min) > 60:
88       raise "Failed","Bad minutes";
89    if Sec != None and float(Sec) > 60:
90       raise "Failed","Bad seconds";
91       
92    # Pad on an extra leading 0 to disambiguate small numbers
93    if len(Deg) <= 1 or Deg[1] == '.':
94       Deg = '0' + Deg;
95    if Min != None and (len(Min) <= 1 or Min[1] == '.'):
96       Min = '0' + Min;
97    if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
98       Sec = '0' + Sec;
99    
100    # Construct a DGM/DGMS type value from the components.
101    Res = "+"
102    if Dr == Dir[1]:
103       Res = "-";
104    Res = Res + Deg;
105    if Min != None:
106       Res = Res + Min;
107    if Sec != None:
108       Res = Res + Sec;
109    return Res;
110               
111 # Handle changing a set of arbitary fields
112 #  <field>: value
113 def DoArbChange(Str,Attrs):
114    Match = re.match("^([^ :]+): (.*)$",Str);
115    if Match == None:
116       return None;
117    G = Match.groups();
118
119    attrName = G[0].lower();
120    for i in ArbChanges.keys():
121       if i.lower() == attrName:
122          attrName = i;
123          break;
124    if ArbChanges.has_key(attrName) == 0:
125       return None;
126
127    if re.match(ArbChanges[attrName],G[1]) == None:
128       raise Error, "Item does not match the required format"+ArbChanges[attrName];
129
130    Attrs.append((ldap.MOD_REPLACE,attrName,G[1]));
131    return "Changed entry %s to %s"%(attrName,G[1]);
132
133 # Handle changing a set of arbitary fields
134 #  <field>: value
135 def DoDel(Str,Attrs):
136    Match = re.match("^del (.*)$",Str);
137    if Match == None:
138       return None;
139    G = Match.groups();
140
141    attrName = G[0].lower();
142    for i in DelItems.keys():
143       if i.lower() == attrName:
144          attrName = i;
145          break;
146    if DelItems.has_key(attrName) == 0:
147       return "Cannot erase entry %s"%(attrName);
148
149    Attrs.append((ldap.MOD_DELETE,attrName,None));
150    return "Removed entry %s"%(attrName);
151
152 # Handle a position change message, the line format is:
153 #  Lat: -12412.23 Long: +12341.2342
154 def DoPosition(Str,Attrs):
155    Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$",string.lower(Str));
156    if Match == None:
157       return None;
158
159    G = Match.groups();
160    try:
161       sLat = LocDecode(G[0],"ns");
162       sLong = LocDecode(G[1],"ew");
163       Lat = DecDegree(sLat,1);
164       Long = DecDegree(sLong,1);
165    except:
166       raise Error, "Positions were found, but they are not correctly formed";
167
168    Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
169    Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
170    return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
171
172 # Handle an SSH authentication key, the line format is:
173 #  [options] 1024 35 13188913666680[..] [comment]
174 def DoSSH(Str,Attrs):
175    Match = SSH2AuthSplit.match(Str);
176    if Match == None:
177       Match = re.compile('^1024 (\d+) ').match(Str)
178       if Match is not None:
179          return "SSH1 keys not supported anymore"
180       return None;
181    
182    global SeenKey;
183    if SeenKey:
184      Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
185      return "SSH Key added "+FormatSSHAuth(Str);
186       
187    Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
188    SeenKey = 1;
189    return "SSH Keys replaced with "+FormatSSHAuth(Str);
190
191 # Handle changing a dns entry
192 #  host in a 12.12.12.12
193 #  host in cname foo.bar.    <- Trailing dot is required
194 def DoDNS(Str,Attrs,DnRecord):
195    cname = re.match("^[-\w]+\s+in\s+cname\s+[-\w.]+\.$",Str,re.IGNORECASE);
196    if re.match('^[-\w]+\s+in\s+a\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',\
197         Str,re.IGNORECASE) == None and cname == None and \
198       re.match("^[-\w]+\s+in\s+mx\s+\d{1,3}\s+[-\w.]+\.$",Str,re.IGNORECASE) == None:
199      return None;     
200
201    # Check if the name is already taken
202    G = re.match('^([-\w+]+)\s',Str).groups();
203
204    # Check for collisions
205    global l;
206    Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"dnsZoneEntry="+G[0]+" *",["uid"]);
207    for x in Rec:
208       if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
209          return "DNS entry is already owned by " + GetAttr(x,"uid")
210
211    global SeenDNS;
212    global DNS;
213
214    if cname:
215      if DNS.has_key(G[0]):
216        return "CNAME and other RR types not allowed: "+Str
217      else:
218        DNS[G[0]] = 2
219    else:
220      if DNS.has_key(G[0]) and DNS[G[0]] == 2:
221        return "CNAME and other RR types not allowed: "+Str
222      else:
223        DNS[G[0]] = 1
224      
225    if SeenDNS:
226      Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",Str));
227      return "DNS Entry added "+Str;
228       
229    Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",Str));
230    SeenDNS = 1;
231    return "DNS Entry replaced with "+Str;
232
233 # Handle an [almost] arbitary change
234 def HandleChange(Reply,DnRecord,Key):
235    global PlainText;
236    Lines = re.split("\n *\r?",PlainText);
237
238    Result = "";
239    Attrs = [];
240    Show = 0;
241    for Line in Lines: 
242       Line = string.strip(Line);
243       if Line == "":
244          continue;
245
246       # Try to process a command line
247       Result = Result + "> "+Line+"\n";
248       try:
249          if Line == "show":
250            Show = 1;
251            Res = "OK";
252          else:
253            Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
254                  DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
255                  DoDel(Line,Attrs);
256       except:
257          Res = None;
258          Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
259          
260       # Fail, if someone tries to send someone elses signed email to the
261       # daemon then we want to abort ASAP.
262       if Res == None:
263          Result = Result + "Command is not understood. Halted\n";
264          break;
265       Result = Result + Res + "\n";
266
267    # Connect to the ldap server
268    l = ldap.open(LDAPServer);
269    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
270    AccessPass = string.split(string.strip(F.readline())," ");
271    F.close();
272
273    # Modify the record
274    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
275    oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
276    if (string.find(GetAttr(oldAttrs[0],"userPassword"),"*LK*")  != -1):
277       raise Error, "This account is locked";
278    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
279    l.modify_s(Dn,Attrs);
280
281    Attribs = "";
282    if Show == 1:
283       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
284       if len(Attrs) == 0:
285          raise Error, "User not found"
286       Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
287       
288    Subst = {};
289    Subst["__FROM__"] = ChangeFrom;
290    Subst["__EMAIL__"] = EmailAddress(DnRecord);
291    Subst["__ADMIN__"] = ReplyTo;
292    Subst["__RESULT__"] = Result;
293    Subst["__ATTR__"] = Attribs;
294
295    return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
296    
297 # Handle ping handles an email sent to the 'ping' address (ie this program
298 # called with a ping argument) It replies with a dump of the public records.
299 def HandlePing(Reply,DnRecord,Key):
300    Subst = {};
301    Subst["__FROM__"] = PingFrom;
302    Subst["__EMAIL__"] = EmailAddress(DnRecord);
303    Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
304    Subst["__ADMIN__"] = ReplyTo;
305
306    return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
307
308 # Handle a change password email sent to the change password address
309 # (this program called with the chpass argument)
310 def HandleChPass(Reply,DnRecord,Key):
311    # Generate a random password
312    Password = GenPass();
313    Pass = HashPass(Password);
314       
315    # Use GPG to encrypt it      
316    Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
317                         "0x"+Key[1],Key[4]);
318    Password = None;
319
320    if Message == None:
321       raise Error, "Unable to generate the encrypted reply, gpg failed.";
322
323    if (Key[4] == 1):
324       Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
325    else:
326       Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
327              "mode, without IDEA. This message cannot be decoded using PGP 2.x";
328    
329    Subst = {};
330    Subst["__FROM__"] = ChPassFrom;
331    Subst["__EMAIL__"] = EmailAddress(DnRecord);
332    Subst["__CRYPTTYPE__"] = Type;
333    Subst["__PASSWORD__"] = Message;
334    Subst["__ADMIN__"] = ReplyTo;
335    Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
336    
337    # Connect to the ldap server
338    l = ldap.open(LDAPServer);
339    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
340    AccessPass = string.split(string.strip(F.readline())," ");
341    F.close();
342    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
343
344    # Check for a locked account
345    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
346    if (string.find(GetAttr(Attrs[0],"userPassword"),"*LK*")  != -1):
347       raise Error, "This account is locked";
348
349    # Modify the password
350    Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
351    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
352    l.modify_s(Dn,Rec);
353
354    return Reply;
355       
356 # Start of main program
357
358 # Drop messages from a mailer daemon.
359 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
360    sys.exit(0);
361
362 ErrMsg = "Indeterminate Error";
363 ErrType = EX_TEMPFAIL;
364 try:
365    # Startup the replay cache
366    ErrType = EX_TEMPFAIL;
367    ErrMsg = "Failed to initialize the replay cache:";
368    RC = ReplayCache(ReplayCacheFile);
369    RC.Clean();
370
371    # Get the email 
372    ErrType = EX_PERMFAIL;
373    ErrMsg = "Failed to understand the email or find a signature:";
374    Email = mimetools.Message(sys.stdin,0);
375    Msg = GetClearSig(Email);
376
377    ErrMsg = "Message is not PGP signed:"
378    if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
379       string.find(Msg[0],"-----BEGIN PGP MESSAGE-----") == -1:
380       raise Error, "No PGP signature";
381    
382    # Check the signature
383    ErrMsg = "Unable to check the signature or the signature was invalid:";
384    Res = GPGCheckSig(Msg[0]);
385
386    if Res[0] != None:
387       raise Error, Res[0];
388       
389    if Res[3] == None:
390       raise Error, "Null signature text";
391
392    # Extract the plain message text in the event of mime encoding
393    global PlainText;
394    ErrMsg = "Problem stripping MIME headers from the decoded message"
395    if Msg[1] == 1:
396       try:
397          Index = string.index(Res[3],"\n\n") + 2;
398       except ValueError:
399          Index = string.index(Res[3],"\n\r\n") + 3;
400       PlainText = Res[3][Index:];
401    else:
402       PlainText = Res[3];   
403
404    # Check the signature against the replay cache
405    ErrMsg = "The replay cache rejected your message. Check your clock!";
406    Rply = RC.Check(Res[1]);
407    if Rply != None:
408       raise Error, Rply;
409
410    # Connect to the ldap server
411    ErrType = EX_TEMPFAIL;
412    ErrMsg = "An error occured while performing the LDAP lookup";
413    global l;
414    l = ldap.open(LDAPServer);
415    l.simple_bind_s("","");
416
417    # Search for the matching key fingerprint
418    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
419
420    ErrType = EX_PERMFAIL;
421    if len(Attrs) == 0:
422       raise Error, "Key not found"
423    if len(Attrs) != 1:
424       raise Error, "Oddly your key fingerprint is assigned to more than one account.."
425
426    RC.Add(Res[1]);
427
428    # Determine the sender address
429    ErrMsg = "A problem occured while trying to formulate the reply";
430    Sender = Email.getheader("Reply-To");
431    if Sender == None:
432       Sender = Email.getheader("From");
433    if Sender == None:
434       raise Error, "Unable to determine the sender's address";
435
436    # Formulate a reply
437    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
438    Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
439
440    # Dispatch
441    if sys.argv[1] == "ping":
442       Reply = HandlePing(Reply,Attrs[0],Res[2]);
443    elif sys.argv[1] == "chpass":
444       if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
445          raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
446       Reply = HandleChPass(Reply,Attrs[0],Res[2]);
447    elif sys.argv[1] == "change":
448       Reply = HandleChange(Reply,Attrs[0],Res[2]);
449    else:
450       print sys.argv;
451       raise Error, "Incorrect Invokation";
452
453    # Send the message through sendmail      
454    ErrMsg = "A problem occured while trying to send the reply";
455    Child = os.popen("/usr/sbin/sendmail -t","w");
456 #   Child = os.popen("cat","w");
457    Child.write(Reply);
458    if Child.close() != None:
459       raise Error, "Sendmail gave a non-zero return code";
460
461 except:
462    # Error Reply Header
463    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
464    ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
465
466    # Error Body
467    Subst = {};
468    Subst["__ERROR__"] = ErrMsg;
469    Subst["__ADMIN__"] = ReplyTo;
470
471    Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
472    List = traceback.extract_tb(sys.exc_traceback);
473    if len(List) > 1:
474       Trace = Trace + "Python Stack Trace:\n";
475       for x in List:
476          Trace = Trace +  "   %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
477
478    Subst["__TRACE__"] = Trace;
479
480    # Try to send the bounce
481    try:
482       ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
483
484       Child = os.popen("/usr/sbin/sendmail -t","w");
485       Child.write(ErrReplyHead);
486       Child.write(ErrReply);
487       if Child.close() != None:
488          raise Error, "Sendmail gave a non-zero return code";
489    except:
490       sys.exit(EX_TEMPFAIL);
491       
492    if ErrType != EX_PERMFAIL:
493       sys.exit(ErrType);
494    sys.exit(0);
495