Fix referer checks with escaped URLs
[cascardo/ipsilon.git] / ipsilon / util / page.py
1 #!/usr/bin/python
2 #
3 # Copyright (C) 2013  Simo Sorce <simo@redhat.com>
4 #
5 # see file 'COPYING' for use and warranty information
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 from ipsilon.util.user import UserSession
21 from urllib import unquote
22 import cherrypy
23
24
25 def admin_protect(fn):
26
27     def check(*args, **kwargs):
28         if UserSession().get_user().is_admin:
29             return fn(*args, **kwargs)
30
31         raise cherrypy.HTTPError(403)
32
33     return check
34
35
36 def protect():
37     UserSession().remote_login()
38
39
40 class Page(object):
41     def __init__(self, site, form=False):
42         if 'template_env' not in site:
43             raise ValueError('Missing template environment')
44         self._site = site
45         self.basepath = cherrypy.config.get('base.mount', "")
46         self.user = None
47         self.form = form
48
49     def _compare_urls(self, url1, url2):
50         u1 = unquote(url1)
51         u2 = unquote(url2)
52         if u1 == u2:
53             return True
54         return False
55
56     def __call__(self, *args, **kwargs):
57         # pylint: disable=star-args
58         self.user = UserSession().get_user()
59
60         if len(args) > 0:
61             op = getattr(self, args[0], None)
62             if callable(op) and getattr(self, args[0]+'.exposed', None):
63                 return op(*args[1:], **kwargs)
64         else:
65             if self.form:
66                 self._debug("method: %s" % cherrypy.request.method)
67                 op = getattr(self, cherrypy.request.method, None)
68                 if callable(op):
69                     # Basic CSRF protection
70                     if cherrypy.request.method != 'GET':
71                         url = cherrypy.url(relative=False)
72                         if 'referer' not in cherrypy.request.headers:
73                             self._debug("Missing referer in %s request to %s"
74                                         % (cherrypy.request.method, url))
75                             raise cherrypy.HTTPError(403)
76                         referer = cherrypy.request.headers['referer']
77                         if not self._compare_urls(referer, url):
78                             self._debug("Wrong referer %s in request to %s"
79                                         % (referer, url))
80                             raise cherrypy.HTTPError(403)
81                     return op(*args, **kwargs)
82             else:
83                 op = getattr(self, 'root', None)
84                 if callable(op):
85                     return op(*args, **kwargs)
86
87         return self.default(*args, **kwargs)
88
89     def _template_model(self):
90         model = dict()
91         model['basepath'] = self.basepath
92         model['title'] = 'IPSILON'
93         model['user'] = self.user
94         return model
95
96     def _template(self, *args, **kwargs):
97         # pylint: disable=star-args
98         t = self._site['template_env'].get_template(args[0])
99         m = self._template_model()
100         m.update(kwargs)
101         return t.render(**m)
102
103     def _debug(self, fact):
104         if cherrypy.config.get('debug', False):
105             cherrypy.log(fact)
106
107     def default(self, *args, **kwargs):
108         raise cherrypy.HTTPError(404)
109
110     def add_subtree(self, name, page):
111         self.__dict__[name] = page
112
113     def del_subtree(self, name):
114         del self.__dict__[name]
115
116     exposed = True