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