[web] add a digital signature to error form (closes #2522526) stable
authorDavid Douard <david.douard@logilab.fr>
Tue, 27 Nov 2012 14:48:03 +0100
branchstable
changeset 8605 797fc2e2fb78
parent 8604 7bacc4f21edc
child 8606 0163bd9f4880
[web] add a digital signature to error form (closes #2522526) Simple (and quite weak) implementation of a digital signature of the content to be submited by email in the error report view generated by ErrorView. The signature is a simple hmac hash computed using a secret key (generated at repository startup) and the "secret" form content to be included in the notification email. The controller can then check this content has not been modified or forged by a malicious user.
web/test/unittest_views_errorform.py
web/views/basecontrollers.py
web/views/management.py
web/webconfig.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/web/test/unittest_views_errorform.py	Tue Nov 27 14:48:03 2012 +0100
@@ -0,0 +1,101 @@
+# copyright 2003-2012 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
+#
+# This file is part of CubicWeb.
+#
+# CubicWeb is free software: you can redistribute it and/or modify it under the
+# terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation, either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# CubicWeb is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Lesser General Public License along
+# with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
+
+from __future__ import with_statement
+
+from logilab.common.testlib import unittest_main
+from logilab.mtconverter import html_unescape
+
+from cubicweb import Forbidden, ValidationError
+from cubicweb.devtools.testlib import CubicWebTC
+from cubicweb.utils import json
+from cubicweb.view import StartupView, TRANSITIONAL_DOCTYPE_NOEXT
+from cubicweb.web import Redirect
+from cubicweb.web.htmlwidgets import TableWidget
+from cubicweb.web.views import vid_from_rset
+
+import re
+import hmac
+
+class ErrorViewTC(CubicWebTC):
+    def setUp(self):
+        super(ErrorViewTC, self).setUp()
+        self.req = self.request()
+        self.vreg.config['submit-mail'] = "test@logilab.fr"
+        self.vreg.config['print-traceback'] = "yes"
+
+    def test_error_generation(self):
+        """
+        tests
+        """
+
+        class MyWrongView(StartupView):
+            __regid__ = 'my-view'
+            def call(self):
+                raise ValueError('This is wrong')
+
+        with self.temporary_appobjects(MyWrongView):
+            try:
+                self.view('my-view')
+            except Exception, e:
+                import sys
+                self.req.data['excinfo'] = sys.exc_info()
+                self.req.data['ex'] = e
+                html = self.view('error', req=self.req)
+                self.failUnless(re.search(r'^<input name="__signature" type="hidden" value="[0-9a-f]{32}" />$',
+                                          html.source, re.M))
+
+
+    def test_error_submit_nosig(self):
+        """
+        tests that the reportbug controller refuses submission if
+        there is not content signature
+        """
+
+        self.req.form = {'description': u'toto',
+                         }
+        with self.assertRaises(Forbidden) as cm:
+            self.ctrl_publish(self.req, 'reportbug')
+
+    def test_error_submit_wrongsig(self):
+        """
+        tests that the reportbug controller refuses submission if the
+        content signature is invalid
+        """
+
+        self.req.form = {'__signature': 'X',
+                         'description': u'toto',
+                         }
+        with self.assertRaises(Forbidden) as cm:
+            self.ctrl_publish(self.req, 'reportbug')
+
+    def test_error_submit_ok(self):
+        """
+        tests that the reportbug controller accept the email submission if the
+        content signature is valid
+        """
+
+        sign = self.vreg.config.sign_text('toto')
+        self.req.form = {'__signature': sign,
+                         'description': u'toto',
+                         }
+        with self.assertRaises(Redirect) as cm:
+            self.ctrl_publish(self.req, 'reportbug')
+
+if __name__ == '__main__':
+    unittest_main()
--- a/web/views/basecontrollers.py	Wed Nov 28 11:44:15 2012 +0100
+++ b/web/views/basecontrollers.py	Tue Nov 27 14:48:03 2012 +0100
@@ -27,7 +27,8 @@
 from logilab.common.deprecation import deprecated
 
 from cubicweb import (NoSelectableObject, ObjectNotFound, ValidationError,
-                      AuthenticationError, typed_eid, UndoTransactionException)
+                      AuthenticationError, typed_eid, UndoTransactionException,
+                      Forbidden)
 from cubicweb.utils import json_dumps
 from cubicweb.predicates import (authenticated_user, anonymous_user,
                                 match_form_params)
@@ -276,9 +277,15 @@
 
     def publish(self, rset=None):
         req = self._cw
+        desc = req.form['description']
+        # The description is generated and signed by cubicweb itself, check
+        # description's signature so we don't want to send spam here
+        sign = req.form.get('__signature', '')
+        if not (sign and req.vreg.config.check_text_sign(desc, sign)):
+            raise Forbidden('Invalid content')
         self.sendmail(req.vreg.config['submit-mail'],
                       req._('%s error report') % req.vreg.config.appid,
-                      req.form['description'])
+                      desc)
         raise Redirect(req.build_url(__message=req._('bug report sent')))
 
 
--- a/web/views/management.py	Wed Nov 28 11:44:15 2012 +0100
+++ b/web/views/management.py	Tue Nov 27 14:48:03 2012 +0100
@@ -20,6 +20,7 @@
 __docformat__ = "restructuredtext en"
 _ = unicode
 
+
 from logilab.mtconverter import xml_escape
 from logilab.common.registry import yes
 
@@ -148,6 +149,8 @@
             form.add_hidden('description', binfo,
                             # we must use a text area to keep line breaks
                             widget=wdgs.TextArea({'class': 'hidden'}))
+            # add a signature so one can't send arbitrary text
+            form.add_hidden('__signature', req.vreg.config.sign_text(binfo))
             form.add_hidden('__bugreporting', '1')
             form.form_buttons = [wdgs.SubmitButton(MAIL_SUBMIT_MSGID)]
             form.action = req.build_url('reportbug')
--- a/web/webconfig.py	Wed Nov 28 11:44:15 2012 +0100
+++ b/web/webconfig.py	Tue Nov 27 14:48:03 2012 +0100
@@ -21,10 +21,12 @@
 _ = unicode
 
 import os
+import hmac
+from uuid import uuid4
 from os.path import join, exists, split, isdir
 from warnings import warn
 
-from logilab.common.decorators import cached
+from logilab.common.decorators import cached, cachedproperty
 from logilab.common.deprecation import deprecated
 
 from cubicweb import ConfigurationError
@@ -272,6 +274,25 @@
             raise ConfigurationError("anonymous information should only contains ascii")
         return user, passwd
 
+    @cachedproperty
+    def _instance_salt(self):
+        """This random key/salt is used to sign content to be sent back by
+        browsers, eg. in the error report form.
+        """
+        return str(uuid4())
+
+    def sign_text(self, text):
+        """sign some text for later checking"""
+        # replace \r\n so we do not depend on whether a browser "reencode"
+        # original message using \r\n or not
+        return hmac.new(self._instance_salt,
+                        text.strip().replace('\r\n', '\n')).hexdigest()
+
+    def check_text_sign(self, text, signature):
+        """check the text signature is equal to the given signature"""
+        return self.sign_text(text) == signature
+
+
     def locate_resource(self, rid):
         """return the (directory, filename) where the given resource
         may be found